cmMakefileTargetGenerator.cxx 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235
  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 "cmMakefileTargetGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cstdio>
  7. #include <iterator>
  8. #include <sstream>
  9. #include <unordered_map>
  10. #include <unordered_set>
  11. #include <utility>
  12. #include <cm/memory>
  13. #include <cm/string_view>
  14. #include <cmext/algorithm>
  15. #include <cmext/string_view>
  16. #include "cmComputeLinkInformation.h"
  17. #include "cmCustomCommand.h"
  18. #include "cmCustomCommandGenerator.h"
  19. #include "cmGeneratedFileStream.h"
  20. #include "cmGeneratorExpression.h"
  21. #include "cmGeneratorTarget.h"
  22. #include "cmGlobalUnixMakefileGenerator3.h"
  23. #include "cmLinkLineComputer.h" // IWYU pragma: keep
  24. #include "cmLocalCommonGenerator.h"
  25. #include "cmLocalGenerator.h"
  26. #include "cmLocalUnixMakefileGenerator3.h"
  27. #include "cmMakefile.h"
  28. #include "cmMakefileExecutableTargetGenerator.h"
  29. #include "cmMakefileLibraryTargetGenerator.h"
  30. #include "cmMakefileUtilityTargetGenerator.h"
  31. #include "cmMessageType.h"
  32. #include "cmOutputConverter.h"
  33. #include "cmPolicies.h"
  34. #include "cmProperty.h"
  35. #include "cmRange.h"
  36. #include "cmRulePlaceholderExpander.h"
  37. #include "cmSourceFile.h"
  38. #include "cmSourceFileLocationKind.h"
  39. #include "cmState.h"
  40. #include "cmStateDirectory.h"
  41. #include "cmStateSnapshot.h"
  42. #include "cmStateTypes.h"
  43. #include "cmStringAlgorithms.h"
  44. #include "cmSystemTools.h"
  45. #include "cmake.h"
  46. cmMakefileTargetGenerator::cmMakefileTargetGenerator(cmGeneratorTarget* target)
  47. : cmCommonTargetGenerator(target)
  48. {
  49. this->CustomCommandDriver = OnBuild;
  50. this->LocalGenerator =
  51. static_cast<cmLocalUnixMakefileGenerator3*>(target->GetLocalGenerator());
  52. this->GlobalGenerator = static_cast<cmGlobalUnixMakefileGenerator3*>(
  53. this->LocalGenerator->GetGlobalGenerator());
  54. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  55. this->NoRuleMessages = false;
  56. if (cmProp ruleStatus = cm->GetState()->GetGlobalProperty("RULE_MESSAGES")) {
  57. this->NoRuleMessages = cmIsOff(*ruleStatus);
  58. }
  59. switch (this->GeneratorTarget->GetPolicyStatusCMP0113()) {
  60. case cmPolicies::WARN:
  61. case cmPolicies::OLD:
  62. this->CMP0113New = false;
  63. break;
  64. case cmPolicies::NEW:
  65. case cmPolicies::REQUIRED_IF_USED:
  66. case cmPolicies::REQUIRED_ALWAYS:
  67. this->CMP0113New = true;
  68. break;
  69. }
  70. this->MacOSXContentGenerator =
  71. cm::make_unique<MacOSXContentGeneratorType>(this);
  72. }
  73. cmMakefileTargetGenerator::~cmMakefileTargetGenerator() = default;
  74. std::unique_ptr<cmMakefileTargetGenerator> cmMakefileTargetGenerator::New(
  75. cmGeneratorTarget* tgt)
  76. {
  77. std::unique_ptr<cmMakefileTargetGenerator> result;
  78. switch (tgt->GetType()) {
  79. case cmStateEnums::EXECUTABLE:
  80. result = cm::make_unique<cmMakefileExecutableTargetGenerator>(tgt);
  81. break;
  82. case cmStateEnums::STATIC_LIBRARY:
  83. case cmStateEnums::SHARED_LIBRARY:
  84. case cmStateEnums::MODULE_LIBRARY:
  85. case cmStateEnums::OBJECT_LIBRARY:
  86. result = cm::make_unique<cmMakefileLibraryTargetGenerator>(tgt);
  87. break;
  88. case cmStateEnums::INTERFACE_LIBRARY:
  89. case cmStateEnums::UTILITY:
  90. result = cm::make_unique<cmMakefileUtilityTargetGenerator>(tgt);
  91. break;
  92. default:
  93. return result;
  94. // break; /* unreachable */
  95. }
  96. return result;
  97. }
  98. std::string cmMakefileTargetGenerator::GetConfigName()
  99. {
  100. auto const& configNames = this->LocalGenerator->GetConfigNames();
  101. assert(configNames.size() == 1);
  102. return configNames.front();
  103. }
  104. void cmMakefileTargetGenerator::GetDeviceLinkFlags(
  105. std::string& linkFlags, const std::string& linkLanguage)
  106. {
  107. cmGeneratorTarget::DeviceLinkSetter setter(*this->GetGeneratorTarget());
  108. std::vector<std::string> linkOpts;
  109. this->GeneratorTarget->GetLinkOptions(linkOpts, this->GetConfigName(),
  110. linkLanguage);
  111. // LINK_OPTIONS are escaped.
  112. this->LocalGenerator->AppendCompileOptions(linkFlags, linkOpts);
  113. }
  114. void cmMakefileTargetGenerator::GetTargetLinkFlags(
  115. std::string& flags, const std::string& linkLanguage)
  116. {
  117. this->LocalGenerator->AppendFlags(
  118. flags, this->GeneratorTarget->GetSafeProperty("LINK_FLAGS"));
  119. std::string linkFlagsConfig =
  120. cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(this->GetConfigName()));
  121. this->LocalGenerator->AppendFlags(
  122. flags, this->GeneratorTarget->GetSafeProperty(linkFlagsConfig));
  123. std::vector<std::string> opts;
  124. this->GeneratorTarget->GetLinkOptions(opts, this->GetConfigName(),
  125. linkLanguage);
  126. // LINK_OPTIONS are escaped.
  127. this->LocalGenerator->AppendCompileOptions(flags, opts);
  128. this->LocalGenerator->AppendPositionIndependentLinkerFlags(
  129. flags, this->GeneratorTarget, this->GetConfigName(), linkLanguage);
  130. }
  131. void cmMakefileTargetGenerator::CreateRuleFile()
  132. {
  133. // Create a directory for this target.
  134. this->TargetBuildDirectory =
  135. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  136. this->TargetBuildDirectoryFull =
  137. this->LocalGenerator->ConvertToFullPath(this->TargetBuildDirectory);
  138. cmSystemTools::MakeDirectory(this->TargetBuildDirectoryFull);
  139. // Construct the rule file name.
  140. this->BuildFileName = cmStrCat(this->TargetBuildDirectory, "/build.make");
  141. this->BuildFileNameFull =
  142. cmStrCat(this->TargetBuildDirectoryFull, "/build.make");
  143. // Construct the rule file name.
  144. this->ProgressFileNameFull =
  145. cmStrCat(this->TargetBuildDirectoryFull, "/progress.make");
  146. // reset the progress count
  147. this->NumberOfProgressActions = 0;
  148. // Open the rule file. This should be copy-if-different because the
  149. // rules may depend on this file itself.
  150. this->BuildFileStream = cm::make_unique<cmGeneratedFileStream>(
  151. this->BuildFileNameFull, false,
  152. this->GlobalGenerator->GetMakefileEncoding());
  153. if (!this->BuildFileStream) {
  154. return;
  155. }
  156. this->BuildFileStream->SetCopyIfDifferent(true);
  157. this->LocalGenerator->WriteDisclaimer(*this->BuildFileStream);
  158. if (this->GlobalGenerator->AllowDeleteOnError()) {
  159. std::vector<std::string> no_depends;
  160. std::vector<std::string> no_commands;
  161. this->LocalGenerator->WriteMakeRule(
  162. *this->BuildFileStream, "Delete rule output on recipe failure.",
  163. ".DELETE_ON_ERROR", no_depends, no_commands, false);
  164. }
  165. this->LocalGenerator->WriteSpecialTargetsTop(*this->BuildFileStream);
  166. }
  167. void cmMakefileTargetGenerator::WriteTargetBuildRules()
  168. {
  169. // -- Write the custom commands for this target
  170. // Evaluates generator expressions and expands prop_value
  171. auto evaluatedFiles =
  172. [this](const std::string& prop_value) -> std::vector<std::string> {
  173. std::vector<std::string> files;
  174. cmExpandList(cmGeneratorExpression::Evaluate(
  175. prop_value, this->LocalGenerator, this->GetConfigName(),
  176. this->GeneratorTarget),
  177. files);
  178. return files;
  179. };
  180. // Look for additional files registered for cleaning in this directory.
  181. if (cmProp prop_value =
  182. this->Makefile->GetProperty("ADDITIONAL_MAKE_CLEAN_FILES")) {
  183. std::vector<std::string> const files = evaluatedFiles(*prop_value);
  184. this->CleanFiles.insert(files.begin(), files.end());
  185. }
  186. // Look for additional files registered for cleaning in this target.
  187. if (cmProp prop_value =
  188. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  189. std::vector<std::string> const files = evaluatedFiles(*prop_value);
  190. // For relative path support
  191. std::string const& binaryDir =
  192. this->LocalGenerator->GetCurrentBinaryDirectory();
  193. for (std::string const& cfl : files) {
  194. this->CleanFiles.insert(cmSystemTools::CollapseFullPath(cfl, binaryDir));
  195. }
  196. }
  197. // Look for ISPC extra object files generated by this target
  198. auto ispcAdditionalObjs =
  199. this->GeneratorTarget->GetGeneratedISPCObjects(this->GetConfigName());
  200. for (std::string const& ispcObj : ispcAdditionalObjs) {
  201. this->CleanFiles.insert(
  202. this->LocalGenerator->MaybeRelativeToCurBinDir(ispcObj));
  203. }
  204. // add custom commands to the clean rules?
  205. bool clean = cmIsOff(this->Makefile->GetProperty("CLEAN_NO_CUSTOM"));
  206. // First generate the object rule files. Save a list of all object
  207. // files for this target.
  208. std::vector<cmSourceFile const*> customCommands;
  209. this->GeneratorTarget->GetCustomCommands(customCommands,
  210. this->GetConfigName());
  211. for (cmSourceFile const* sf : customCommands) {
  212. if (this->CMP0113New &&
  213. !this->LocalGenerator->GetCommandsVisited(this->GeneratorTarget)
  214. .insert(sf)
  215. .second) {
  216. continue;
  217. }
  218. cmCustomCommandGenerator ccg(*sf->GetCustomCommand(),
  219. this->GetConfigName(), this->LocalGenerator);
  220. this->GenerateCustomRuleFile(ccg);
  221. if (clean) {
  222. const std::vector<std::string>& outputs = ccg.GetOutputs();
  223. for (std::string const& output : outputs) {
  224. this->CleanFiles.insert(
  225. this->LocalGenerator->MaybeRelativeToCurBinDir(output));
  226. }
  227. const std::vector<std::string>& byproducts = ccg.GetByproducts();
  228. for (std::string const& byproduct : byproducts) {
  229. this->CleanFiles.insert(
  230. this->LocalGenerator->MaybeRelativeToCurBinDir(byproduct));
  231. }
  232. }
  233. }
  234. // Add byproducts from build events to the clean rules
  235. if (clean) {
  236. std::vector<cmCustomCommand> buildEventCommands =
  237. this->GeneratorTarget->GetPreBuildCommands();
  238. cm::append(buildEventCommands,
  239. this->GeneratorTarget->GetPreLinkCommands());
  240. cm::append(buildEventCommands,
  241. this->GeneratorTarget->GetPostBuildCommands());
  242. for (const auto& be : buildEventCommands) {
  243. cmCustomCommandGenerator beg(be, this->GetConfigName(),
  244. this->LocalGenerator);
  245. const std::vector<std::string>& byproducts = beg.GetByproducts();
  246. for (std::string const& byproduct : byproducts) {
  247. this->CleanFiles.insert(
  248. this->LocalGenerator->MaybeRelativeToCurBinDir(byproduct));
  249. }
  250. }
  251. }
  252. std::vector<cmSourceFile const*> headerSources;
  253. this->GeneratorTarget->GetHeaderSources(headerSources,
  254. this->GetConfigName());
  255. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  256. headerSources, this->MacOSXContentGenerator.get(), this->GetConfigName());
  257. std::vector<cmSourceFile const*> extraSources;
  258. this->GeneratorTarget->GetExtraSources(extraSources, this->GetConfigName());
  259. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  260. extraSources, this->MacOSXContentGenerator.get(), this->GetConfigName());
  261. cmProp pchExtension = this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  262. std::vector<cmSourceFile const*> externalObjects;
  263. this->GeneratorTarget->GetExternalObjects(externalObjects,
  264. this->GetConfigName());
  265. for (cmSourceFile const* sf : externalObjects) {
  266. auto const& objectFileName = sf->GetFullPath();
  267. if (!cmSystemTools::StringEndsWith(objectFileName,
  268. cmToCStr(pchExtension))) {
  269. this->ExternalObjects.push_back(objectFileName);
  270. }
  271. }
  272. std::vector<cmSourceFile const*> objectSources;
  273. this->GeneratorTarget->GetObjectSources(objectSources,
  274. this->GetConfigName());
  275. for (cmSourceFile const* sf : objectSources) {
  276. // Generate this object file's rule file.
  277. this->WriteObjectRuleFiles(*sf);
  278. }
  279. }
  280. void cmMakefileTargetGenerator::WriteCommonCodeRules()
  281. {
  282. const char* root = (this->Makefile->IsOn("CMAKE_MAKE_INCLUDE_FROM_ROOT")
  283. ? "$(CMAKE_BINARY_DIR)/"
  284. : "");
  285. // Include the dependencies for the target.
  286. std::string dependFileNameFull =
  287. cmStrCat(this->TargetBuildDirectoryFull, "/depend.make");
  288. *this->BuildFileStream
  289. << "# Include any dependencies generated for this target.\n"
  290. << this->GlobalGenerator->IncludeDirective << " " << root
  291. << cmSystemTools::ConvertToOutputPath(
  292. this->LocalGenerator->MaybeRelativeToTopBinDir(dependFileNameFull))
  293. << "\n";
  294. std::string depsUseCompiler = "CMAKE_DEPENDS_USE_COMPILER";
  295. if (!this->Makefile->IsDefinitionSet(depsUseCompiler) ||
  296. this->Makefile->IsOn(depsUseCompiler)) {
  297. std::string compilerDependFile =
  298. cmStrCat(this->TargetBuildDirectoryFull, "/compiler_depend.make");
  299. *this->BuildFileStream << "# Include any dependencies generated by the "
  300. "compiler for this target.\n"
  301. << this->GlobalGenerator->IncludeDirective << " "
  302. << root
  303. << cmSystemTools::ConvertToOutputPath(
  304. this->LocalGenerator->MaybeRelativeToTopBinDir(
  305. compilerDependFile))
  306. << "\n\n";
  307. // Write an empty dependency file.
  308. cmGeneratedFileStream depFileStream(
  309. compilerDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  310. depFileStream << "# Empty compiler generated dependencies file for "
  311. << this->GeneratorTarget->GetName() << ".\n"
  312. << "# This may be replaced when dependencies are built.\n";
  313. // remove internal dependency file
  314. cmSystemTools::RemoveFile(
  315. cmStrCat(this->TargetBuildDirectoryFull, "/compiler_depend.internal"));
  316. std::string compilerDependTimestamp =
  317. cmStrCat(this->TargetBuildDirectoryFull, "/compiler_depend.ts");
  318. if (!cmSystemTools::FileExists(compilerDependTimestamp)) {
  319. // Write a dependency timestamp file.
  320. cmGeneratedFileStream timestampFileStream(
  321. compilerDependTimestamp, false,
  322. this->GlobalGenerator->GetMakefileEncoding());
  323. timestampFileStream
  324. << "# CMAKE generated file: DO NOT EDIT!\n"
  325. << "# Timestamp file for compiler generated dependencies "
  326. "management for "
  327. << this->GeneratorTarget->GetName() << ".\n";
  328. }
  329. // deactivate no longer needed legacy dependency files
  330. // Write an empty dependency file.
  331. cmGeneratedFileStream legacyDepFileStream(
  332. dependFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
  333. legacyDepFileStream
  334. << "# Empty dependencies file for " << this->GeneratorTarget->GetName()
  335. << ".\n"
  336. << "# This may be replaced when dependencies are built.\n";
  337. // remove internal dependency file
  338. cmSystemTools::RemoveFile(
  339. cmStrCat(this->TargetBuildDirectoryFull, "/depend.internal"));
  340. } else {
  341. // make sure the depend file exists
  342. if (!cmSystemTools::FileExists(dependFileNameFull)) {
  343. // Write an empty dependency file.
  344. cmGeneratedFileStream depFileStream(
  345. dependFileNameFull, false,
  346. this->GlobalGenerator->GetMakefileEncoding());
  347. depFileStream << "# Empty dependencies file for "
  348. << this->GeneratorTarget->GetName() << ".\n"
  349. << "# This may be replaced when dependencies are built.\n";
  350. }
  351. }
  352. if (!this->NoRuleMessages) {
  353. // Include the progress variables for the target.
  354. *this->BuildFileStream
  355. << "# Include the progress variables for this target.\n"
  356. << this->GlobalGenerator->IncludeDirective << " " << root
  357. << cmSystemTools::ConvertToOutputPath(
  358. this->LocalGenerator->MaybeRelativeToTopBinDir(
  359. this->ProgressFileNameFull))
  360. << "\n\n";
  361. }
  362. // Open the flags file. This should be copy-if-different because the
  363. // rules may depend on this file itself.
  364. this->FlagFileNameFull =
  365. cmStrCat(this->TargetBuildDirectoryFull, "/flags.make");
  366. this->FlagFileStream = cm::make_unique<cmGeneratedFileStream>(
  367. this->FlagFileNameFull, false,
  368. this->GlobalGenerator->GetMakefileEncoding());
  369. if (!this->FlagFileStream) {
  370. return;
  371. }
  372. this->FlagFileStream->SetCopyIfDifferent(true);
  373. this->LocalGenerator->WriteDisclaimer(*this->FlagFileStream);
  374. // Include the flags for the target.
  375. *this->BuildFileStream
  376. << "# Include the compile flags for this target's objects.\n"
  377. << this->GlobalGenerator->IncludeDirective << " " << root
  378. << cmSystemTools::ConvertToOutputPath(
  379. this->LocalGenerator->MaybeRelativeToTopBinDir(
  380. this->FlagFileNameFull))
  381. << "\n\n";
  382. }
  383. void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
  384. {
  385. // write language flags for target
  386. std::set<std::string> languages;
  387. this->GeneratorTarget->GetLanguages(
  388. languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  389. // put the compiler in the rules.make file so that if it changes
  390. // things rebuild
  391. for (std::string const& language : languages) {
  392. std::string compiler = cmStrCat("CMAKE_", language, "_COMPILER");
  393. *this->FlagFileStream << "# compile " << language << " with "
  394. << this->Makefile->GetSafeDefinition(compiler)
  395. << "\n";
  396. }
  397. bool const escapeOctothorpe = this->GlobalGenerator->CanEscapeOctothorpe();
  398. for (std::string const& language : languages) {
  399. std::string defines = this->GetDefines(language, this->GetConfigName());
  400. std::string includes = this->GetIncludes(language, this->GetConfigName());
  401. if (escapeOctothorpe) {
  402. // Escape comment characters so they do not terminate assignment.
  403. cmSystemTools::ReplaceString(defines, "#", "\\#");
  404. cmSystemTools::ReplaceString(includes, "#", "\\#");
  405. }
  406. *this->FlagFileStream << language << "_DEFINES = " << defines << "\n\n";
  407. *this->FlagFileStream << language << "_INCLUDES = " << includes << "\n\n";
  408. std::vector<std::string> architectures;
  409. this->GeneratorTarget->GetAppleArchs(this->GetConfigName(), architectures);
  410. architectures.emplace_back();
  411. for (const std::string& arch : architectures) {
  412. std::string flags =
  413. this->GetFlags(language, this->GetConfigName(), arch);
  414. if (escapeOctothorpe) {
  415. cmSystemTools::ReplaceString(flags, "#", "\\#");
  416. }
  417. *this->FlagFileStream << language << "_FLAGS" << arch << " = " << flags
  418. << "\n\n";
  419. }
  420. }
  421. }
  422. void cmMakefileTargetGenerator::MacOSXContentGeneratorType::operator()(
  423. cmSourceFile const& source, const char* pkgloc, const std::string& config)
  424. {
  425. // Skip OS X content when not building a Framework or Bundle.
  426. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  427. return;
  428. }
  429. std::string macdir =
  430. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc,
  431. config);
  432. // Get the input file location.
  433. std::string const& input = source.GetFullPath();
  434. // Get the output file location.
  435. std::string output =
  436. cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input));
  437. this->Generator->CleanFiles.insert(
  438. this->Generator->LocalGenerator->MaybeRelativeToCurBinDir(output));
  439. output = this->Generator->LocalGenerator->MaybeRelativeToTopBinDir(output);
  440. // Create a rule to copy the content into the bundle.
  441. std::vector<std::string> depends;
  442. std::vector<std::string> commands;
  443. depends.push_back(input);
  444. std::string copyEcho = cmStrCat("Copying OS X content ", output);
  445. this->Generator->LocalGenerator->AppendEcho(
  446. commands, copyEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  447. std::string copyCommand =
  448. cmStrCat("$(CMAKE_COMMAND) -E copy ",
  449. this->Generator->LocalGenerator->ConvertToOutputFormat(
  450. input, cmOutputConverter::SHELL),
  451. ' ',
  452. this->Generator->LocalGenerator->ConvertToOutputFormat(
  453. output, cmOutputConverter::SHELL));
  454. commands.push_back(std::move(copyCommand));
  455. this->Generator->LocalGenerator->WriteMakeRule(
  456. *this->Generator->BuildFileStream, nullptr, output, depends, commands,
  457. false);
  458. this->Generator->ExtraFiles.insert(output);
  459. }
  460. void cmMakefileTargetGenerator::WriteObjectRuleFiles(
  461. cmSourceFile const& source)
  462. {
  463. // Identify the language of the source file.
  464. const std::string& lang =
  465. this->LocalGenerator->GetSourceFileLanguage(source);
  466. if (lang.empty()) {
  467. // don't know anything about this file so skip it
  468. return;
  469. }
  470. // Use compiler to generate dependencies, if supported.
  471. bool compilerGenerateDeps =
  472. this->GlobalGenerator->SupportsCompilerDependencies() &&
  473. cmIsOn(this->Makefile->GetDefinition(
  474. cmStrCat("CMAKE_", lang, "_DEPENDS_USE_COMPILER")));
  475. auto scanner = compilerGenerateDeps ? cmDependencyScannerKind::Compiler
  476. : cmDependencyScannerKind::CMake;
  477. // Get the full path name of the object file.
  478. std::string const& objectName =
  479. this->GeneratorTarget->GetObjectName(&source);
  480. std::string obj =
  481. cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  482. '/', objectName);
  483. // Avoid generating duplicate rules.
  484. if (this->ObjectFiles.find(obj) == this->ObjectFiles.end()) {
  485. this->ObjectFiles.insert(obj);
  486. } else {
  487. std::ostringstream err;
  488. err << "Warning: Source file \"" << source.GetFullPath()
  489. << "\" is listed multiple times for target \""
  490. << this->GeneratorTarget->GetName() << "\".";
  491. cmSystemTools::Message(err.str(), "Warning");
  492. return;
  493. }
  494. // Create the directory containing the object file. This may be a
  495. // subdirectory under the target's directory.
  496. {
  497. std::string dir = cmSystemTools::GetFilenamePath(obj);
  498. cmSystemTools::MakeDirectory(this->LocalGenerator->ConvertToFullPath(dir));
  499. }
  500. // Save this in the target's list of object files.
  501. this->Objects.push_back(obj);
  502. this->CleanFiles.insert(obj);
  503. std::vector<std::string> depends;
  504. // The object file should be checked for dependency integrity.
  505. std::string objFullPath =
  506. cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', obj);
  507. objFullPath = cmSystemTools::CollapseFullPath(objFullPath);
  508. std::string srcFullPath =
  509. cmSystemTools::CollapseFullPath(source.GetFullPath());
  510. this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, lang,
  511. objFullPath, srcFullPath, scanner);
  512. this->LocalGenerator->AppendRuleDepend(depends,
  513. this->FlagFileNameFull.c_str());
  514. this->LocalGenerator->AppendRuleDepends(depends,
  515. this->FlagFileDepends[lang]);
  516. // generate the depend scanning rule
  517. this->WriteObjectDependRules(source, depends);
  518. std::string config = this->GetConfigName();
  519. std::string configUpper = cmSystemTools::UpperCase(config);
  520. // Add precompile headers dependencies
  521. std::vector<std::string> architectures;
  522. this->GeneratorTarget->GetAppleArchs(config, architectures);
  523. if (architectures.empty()) {
  524. architectures.emplace_back();
  525. }
  526. std::string filterArch;
  527. std::unordered_map<std::string, std::string> pchSources;
  528. for (const std::string& arch : architectures) {
  529. const std::string pchSource =
  530. this->GeneratorTarget->GetPchSource(config, lang, arch);
  531. if (pchSource == source.GetFullPath()) {
  532. filterArch = arch;
  533. }
  534. if (!pchSource.empty()) {
  535. pchSources.insert(std::make_pair(pchSource, arch));
  536. }
  537. }
  538. if (!pchSources.empty() && !source.GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  539. for (const std::string& arch : architectures) {
  540. std::string const& pchHeader =
  541. this->GeneratorTarget->GetPchHeader(config, lang, arch);
  542. depends.push_back(pchHeader);
  543. if (pchSources.find(source.GetFullPath()) == pchSources.end()) {
  544. depends.push_back(
  545. this->GeneratorTarget->GetPchFile(config, lang, arch));
  546. }
  547. this->LocalGenerator->AddImplicitDepends(
  548. this->GeneratorTarget, lang, objFullPath, pchHeader, scanner);
  549. }
  550. }
  551. if (lang != "ISPC") {
  552. auto const& headers =
  553. this->GeneratorTarget->GetGeneratedISPCHeaders(config);
  554. if (!headers.empty()) {
  555. depends.insert(depends.end(), headers.begin(), headers.end());
  556. }
  557. }
  558. std::string relativeObj =
  559. cmStrCat(this->LocalGenerator->GetHomeRelativeOutputPath(), obj);
  560. // Write the build rule.
  561. // Build the set of compiler flags.
  562. std::string flags;
  563. // Explicitly add the explicit language flag before any other flag
  564. // so user flags can override it.
  565. this->GeneratorTarget->AddExplicitLanguageFlags(flags, source);
  566. // Add language-specific flags.
  567. std::string langFlags = cmStrCat("$(", lang, "_FLAGS", filterArch, ")");
  568. this->LocalGenerator->AppendFlags(flags, langFlags);
  569. cmGeneratorExpressionInterpreter genexInterpreter(
  570. this->LocalGenerator, config, this->GeneratorTarget, lang);
  571. // Add Fortran format flags.
  572. if (lang == "Fortran") {
  573. this->AppendFortranFormatFlags(flags, source);
  574. this->AppendFortranPreprocessFlags(flags, source);
  575. }
  576. std::string ispcHeaderRelative;
  577. std::string ispcHeaderForShell;
  578. if (lang == "ISPC") {
  579. std::string ispcSource =
  580. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  581. ispcSource = cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  582. cmProp ispcSuffixProp =
  583. this->GeneratorTarget->GetProperty("ISPC_HEADER_SUFFIX");
  584. assert(ispcSuffixProp);
  585. std::string directory = this->GeneratorTarget->GetObjectDirectory(config);
  586. if (cmProp prop =
  587. this->GeneratorTarget->GetProperty("ISPC_HEADER_DIRECTORY")) {
  588. directory =
  589. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), '/', *prop);
  590. }
  591. ispcHeaderRelative = cmStrCat(directory, '/', ispcSource, *ispcSuffixProp);
  592. ispcHeaderForShell = this->LocalGenerator->ConvertToOutputFormat(
  593. ispcHeaderRelative, cmOutputConverter::SHELL);
  594. }
  595. // Add flags from source file properties.
  596. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  597. if (cmProp cflags = source.GetProperty(COMPILE_FLAGS)) {
  598. const std::string& evaluatedFlags =
  599. genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS);
  600. this->LocalGenerator->AppendFlags(flags, evaluatedFlags);
  601. *this->FlagFileStream << "# Custom flags: " << relativeObj
  602. << "_FLAGS = " << evaluatedFlags << "\n"
  603. << "\n";
  604. }
  605. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  606. if (cmProp coptions = source.GetProperty(COMPILE_OPTIONS)) {
  607. const std::string& evaluatedOptions =
  608. genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS);
  609. this->LocalGenerator->AppendCompileOptions(flags, evaluatedOptions);
  610. *this->FlagFileStream << "# Custom options: " << relativeObj
  611. << "_OPTIONS = " << evaluatedOptions << "\n"
  612. << "\n";
  613. }
  614. // Add precompile headers compile options.
  615. if (!pchSources.empty() && !source.GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  616. std::string pchOptions;
  617. auto pchIt = pchSources.find(source.GetFullPath());
  618. if (pchIt != pchSources.end()) {
  619. pchOptions = this->GeneratorTarget->GetPchCreateCompileOptions(
  620. config, lang, pchIt->second);
  621. } else {
  622. pchOptions =
  623. this->GeneratorTarget->GetPchUseCompileOptions(config, lang);
  624. }
  625. const std::string& evaluatedFlags =
  626. genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS);
  627. this->LocalGenerator->AppendCompileOptions(flags, evaluatedFlags);
  628. *this->FlagFileStream << "# PCH options: " << relativeObj
  629. << "_OPTIONS = " << evaluatedFlags << "\n"
  630. << "\n";
  631. }
  632. // Add include directories from source file properties.
  633. std::vector<std::string> includes;
  634. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  635. if (cmProp cincludes = source.GetProperty(INCLUDE_DIRECTORIES)) {
  636. const std::string& evaluatedIncludes =
  637. genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES);
  638. this->LocalGenerator->AppendIncludeDirectories(includes, evaluatedIncludes,
  639. source);
  640. *this->FlagFileStream << "# Custom include directories: " << relativeObj
  641. << "_INCLUDE_DIRECTORIES = " << evaluatedIncludes
  642. << "\n"
  643. << "\n";
  644. }
  645. // Add language-specific defines.
  646. std::set<std::string> defines;
  647. // Add source-specific preprocessor definitions.
  648. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  649. if (cmProp compile_defs = source.GetProperty(COMPILE_DEFINITIONS)) {
  650. const std::string& evaluatedDefs =
  651. genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS);
  652. this->LocalGenerator->AppendDefines(defines, evaluatedDefs);
  653. *this->FlagFileStream << "# Custom defines: " << relativeObj
  654. << "_DEFINES = " << evaluatedDefs << "\n"
  655. << "\n";
  656. }
  657. std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper);
  658. if (cmProp config_compile_defs = source.GetProperty(defPropName)) {
  659. const std::string& evaluatedDefs =
  660. genexInterpreter.Evaluate(*config_compile_defs, COMPILE_DEFINITIONS);
  661. this->LocalGenerator->AppendDefines(defines, evaluatedDefs);
  662. *this->FlagFileStream << "# Custom defines: " << relativeObj << "_DEFINES_"
  663. << configUpper << " = " << evaluatedDefs << "\n"
  664. << "\n";
  665. }
  666. // Get the output paths for source and object files.
  667. std::string sourceFile = this->LocalGenerator->ConvertToOutputFormat(
  668. source.GetFullPath(), cmOutputConverter::SHELL);
  669. // Construct the build message.
  670. std::vector<std::string> no_depends;
  671. std::vector<std::string> commands;
  672. // add in a progress call if needed
  673. this->NumberOfProgressActions++;
  674. if (!this->NoRuleMessages) {
  675. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  676. this->MakeEchoProgress(progress);
  677. std::string buildEcho =
  678. cmStrCat("Building ", lang, " object ", relativeObj);
  679. this->LocalGenerator->AppendEcho(commands, buildEcho,
  680. cmLocalUnixMakefileGenerator3::EchoBuild,
  681. &progress);
  682. }
  683. std::string targetOutPathReal;
  684. std::string targetOutPathPDB;
  685. std::string targetOutPathCompilePDB;
  686. {
  687. std::string targetFullPathReal;
  688. std::string targetFullPathPDB;
  689. std::string targetFullPathCompilePDB =
  690. this->ComputeTargetCompilePDB(this->GetConfigName());
  691. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  692. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  693. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  694. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  695. targetFullPathReal = this->GeneratorTarget->GetFullPath(
  696. this->GetConfigName(), cmStateEnums::RuntimeBinaryArtifact, true);
  697. targetFullPathPDB = cmStrCat(
  698. this->GeneratorTarget->GetPDBDirectory(this->GetConfigName()), '/',
  699. this->GeneratorTarget->GetPDBName(this->GetConfigName()));
  700. }
  701. targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
  702. this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathReal),
  703. cmOutputConverter::SHELL);
  704. targetOutPathPDB = this->LocalGenerator->ConvertToOutputFormat(
  705. targetFullPathPDB, cmOutputConverter::SHELL);
  706. targetOutPathCompilePDB = this->LocalGenerator->ConvertToOutputFormat(
  707. this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathCompilePDB),
  708. cmOutputConverter::SHELL);
  709. if (this->LocalGenerator->IsMinGWMake() &&
  710. cmHasLiteralSuffix(targetOutPathCompilePDB, "\\")) {
  711. // mingw32-make incorrectly interprets 'a\ b c' as 'a b' and 'c'
  712. // (but 'a\ b "c"' as 'a\', 'b', and 'c'!). Workaround this by
  713. // avoiding a trailing backslash in the argument.
  714. targetOutPathCompilePDB.back() = '/';
  715. }
  716. std::string compilePdbOutputPath =
  717. this->GeneratorTarget->GetCompilePDBDirectory(this->GetConfigName());
  718. cmSystemTools::MakeDirectory(compilePdbOutputPath);
  719. }
  720. cmRulePlaceholderExpander::RuleVariables vars;
  721. vars.CMTargetName = this->GeneratorTarget->GetName().c_str();
  722. vars.CMTargetType =
  723. cmState::GetTargetTypeName(this->GeneratorTarget->GetType()).c_str();
  724. vars.Language = lang.c_str();
  725. vars.Target = targetOutPathReal.c_str();
  726. vars.TargetPDB = targetOutPathPDB.c_str();
  727. vars.TargetCompilePDB = targetOutPathCompilePDB.c_str();
  728. vars.Source = sourceFile.c_str();
  729. std::string shellObj =
  730. this->LocalGenerator->ConvertToOutputFormat(obj, cmOutputConverter::SHELL);
  731. vars.Object = shellObj.c_str();
  732. std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
  733. objectDir = this->LocalGenerator->ConvertToOutputFormat(
  734. this->LocalGenerator->MaybeRelativeToCurBinDir(objectDir),
  735. cmOutputConverter::SHELL);
  736. vars.ObjectDir = objectDir.c_str();
  737. std::string objectFileDir = cmSystemTools::GetFilenamePath(obj);
  738. objectFileDir = this->LocalGenerator->ConvertToOutputFormat(
  739. this->LocalGenerator->MaybeRelativeToCurBinDir(objectFileDir),
  740. cmOutputConverter::SHELL);
  741. vars.ObjectFileDir = objectFileDir.c_str();
  742. vars.Flags = flags.c_str();
  743. vars.ISPCHeader = ispcHeaderForShell.c_str();
  744. std::string definesString = cmStrCat("$(", lang, "_DEFINES)");
  745. this->LocalGenerator->JoinDefines(defines, definesString, lang);
  746. vars.Defines = definesString.c_str();
  747. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  748. includes, this->GeneratorTarget, lang, config);
  749. this->LocalGenerator->AppendFlags(includesString,
  750. "$(" + lang + "_INCLUDES)");
  751. vars.Includes = includesString.c_str();
  752. std::string dependencyTarget;
  753. std::string shellDependencyFile;
  754. std::string dependencyTimestamp;
  755. if (compilerGenerateDeps) {
  756. dependencyTarget = this->LocalGenerator->EscapeForShell(
  757. this->LocalGenerator->ConvertToMakefilePath(
  758. this->LocalGenerator->MaybeRelativeToTopBinDir(relativeObj)));
  759. vars.DependencyTarget = dependencyTarget.c_str();
  760. auto depFile = cmStrCat(obj, ".d");
  761. shellDependencyFile = this->LocalGenerator->ConvertToOutputFormat(
  762. depFile, cmOutputConverter::SHELL);
  763. vars.DependencyFile = shellDependencyFile.c_str();
  764. this->CleanFiles.insert(depFile);
  765. dependencyTimestamp = this->LocalGenerator->MaybeRelativeToTopBinDir(
  766. cmStrCat(this->TargetBuildDirectoryFull, "/compiler_depend.ts"));
  767. }
  768. // At the moment, it is assumed that C, C++, Fortran, and CUDA have both
  769. // assembly and preprocessor capabilities. The same is true for the
  770. // ability to export compile commands
  771. bool lang_has_preprocessor =
  772. ((lang == "C") || (lang == "CXX") || (lang == "OBJC") ||
  773. (lang == "OBJCXX") || (lang == "Fortran") || (lang == "CUDA") ||
  774. lang == "ISPC" || lang == "ASM");
  775. bool const lang_has_assembly = lang_has_preprocessor;
  776. bool const lang_can_export_cmds = lang_has_preprocessor;
  777. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  778. this->LocalGenerator->CreateRulePlaceholderExpander());
  779. // Construct the compile rules.
  780. {
  781. std::vector<std::string> compileCommands;
  782. if (lang == "CUDA") {
  783. std::string cmdVar;
  784. if (this->GeneratorTarget->GetPropertyAsBool(
  785. "CUDA_SEPARABLE_COMPILATION")) {
  786. cmdVar = "CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION";
  787. } else if (this->GeneratorTarget->GetPropertyAsBool(
  788. "CUDA_PTX_COMPILATION")) {
  789. cmdVar = "CMAKE_CUDA_COMPILE_PTX_COMPILATION";
  790. } else {
  791. cmdVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION";
  792. }
  793. const std::string& compileRule =
  794. this->Makefile->GetRequiredDefinition(cmdVar);
  795. cmExpandList(compileRule, compileCommands);
  796. } else {
  797. const std::string cmdVar = "CMAKE_" + lang + "_COMPILE_OBJECT";
  798. const std::string& compileRule =
  799. this->Makefile->GetRequiredDefinition(cmdVar);
  800. cmExpandList(compileRule, compileCommands);
  801. }
  802. if (this->GeneratorTarget->GetPropertyAsBool("EXPORT_COMPILE_COMMANDS") &&
  803. lang_can_export_cmds && compileCommands.size() == 1) {
  804. std::string compileCommand = compileCommands[0];
  805. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  806. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  807. compileCommand, vars);
  808. std::string workingDirectory =
  809. this->LocalGenerator->GetCurrentBinaryDirectory();
  810. std::string::size_type lfPos = compileCommand.find(langFlags);
  811. if (lfPos != std::string::npos) {
  812. compileCommand.replace(lfPos, langFlags.size(),
  813. this->GetFlags(lang, this->GetConfigName()));
  814. }
  815. std::string langDefines = std::string("$(") + lang + "_DEFINES)";
  816. std::string::size_type ldPos = compileCommand.find(langDefines);
  817. if (ldPos != std::string::npos) {
  818. compileCommand.replace(ldPos, langDefines.size(),
  819. this->GetDefines(lang, this->GetConfigName()));
  820. }
  821. std::string langIncludes = std::string("$(") + lang + "_INCLUDES)";
  822. std::string::size_type liPos = compileCommand.find(langIncludes);
  823. if (liPos != std::string::npos) {
  824. compileCommand.replace(liPos, langIncludes.size(),
  825. this->GetIncludes(lang, this->GetConfigName()));
  826. }
  827. cmProp eliminate[] = {
  828. this->Makefile->GetDefinition("CMAKE_START_TEMP_FILE"),
  829. this->Makefile->GetDefinition("CMAKE_END_TEMP_FILE")
  830. };
  831. for (cmProp el : eliminate) {
  832. if (el) {
  833. cmSystemTools::ReplaceString(compileCommand, *el, "");
  834. }
  835. }
  836. this->GlobalGenerator->AddCXXCompileCommand(
  837. source.GetFullPath(), workingDirectory, compileCommand);
  838. }
  839. // See if we need to use a compiler launcher like ccache or distcc
  840. std::string compilerLauncher;
  841. if (!compileCommands.empty() &&
  842. (lang == "C" || lang == "CXX" || lang == "Fortran" || lang == "CUDA" ||
  843. lang == "ISPC" || lang == "OBJC" || lang == "OBJCXX")) {
  844. std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER";
  845. cmProp clauncher = this->GeneratorTarget->GetProperty(clauncher_prop);
  846. if (cmNonempty(clauncher)) {
  847. compilerLauncher = *clauncher;
  848. }
  849. }
  850. // Maybe insert an include-what-you-use runner.
  851. if (!compileCommands.empty() &&
  852. (lang == "C" || lang == "CXX" || lang == "OBJC" || lang == "OBJCXX")) {
  853. std::string const tidy_prop = lang + "_CLANG_TIDY";
  854. cmProp tidy = this->GeneratorTarget->GetProperty(tidy_prop);
  855. cmProp iwyu = nullptr;
  856. cmProp cpplint = nullptr;
  857. cmProp cppcheck = nullptr;
  858. if (lang == "C" || lang == "CXX") {
  859. std::string const iwyu_prop = lang + "_INCLUDE_WHAT_YOU_USE";
  860. iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
  861. std::string const cpplint_prop = lang + "_CPPLINT";
  862. cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
  863. std::string const cppcheck_prop = lang + "_CPPCHECK";
  864. cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
  865. }
  866. if (cmNonempty(iwyu) || cmNonempty(tidy) || cmNonempty(cpplint) ||
  867. cmNonempty(cppcheck)) {
  868. std::string run_iwyu = "$(CMAKE_COMMAND) -E __run_co_compile";
  869. if (!compilerLauncher.empty()) {
  870. // In __run_co_compile case the launcher command is supplied
  871. // via --launcher=<maybe-list> and consumed
  872. run_iwyu += " --launcher=";
  873. run_iwyu += this->LocalGenerator->EscapeForShell(compilerLauncher);
  874. compilerLauncher.clear();
  875. }
  876. if (cmNonempty(iwyu)) {
  877. run_iwyu += " --iwyu=";
  878. run_iwyu += this->LocalGenerator->EscapeForShell(*iwyu);
  879. }
  880. if (cmNonempty(tidy)) {
  881. run_iwyu += " --tidy=";
  882. cmProp p = this->Makefile->GetDefinition("CMAKE_" + lang +
  883. "_CLANG_TIDY_DRIVER_MODE");
  884. std::string driverMode;
  885. if (cmNonempty(p)) {
  886. driverMode = *p;
  887. } else {
  888. driverMode = lang == "C" ? "gcc" : "g++";
  889. }
  890. run_iwyu += this->LocalGenerator->EscapeForShell(
  891. cmStrCat(*tidy, ";--extra-arg-before=--driver-mode=", driverMode));
  892. }
  893. if (cmNonempty(cpplint)) {
  894. run_iwyu += " --cpplint=";
  895. run_iwyu += this->LocalGenerator->EscapeForShell(*cpplint);
  896. }
  897. if (cmNonempty(cppcheck)) {
  898. run_iwyu += " --cppcheck=";
  899. run_iwyu += this->LocalGenerator->EscapeForShell(*cppcheck);
  900. }
  901. if (cmNonempty(tidy) || (cmNonempty(cpplint)) ||
  902. (cmNonempty(cppcheck))) {
  903. run_iwyu += " --source=";
  904. run_iwyu += sourceFile;
  905. }
  906. run_iwyu += " -- ";
  907. compileCommands.front().insert(0, run_iwyu);
  908. }
  909. }
  910. // If compiler launcher was specified and not consumed above, it
  911. // goes to the beginning of the command line.
  912. if (!compileCommands.empty() && !compilerLauncher.empty()) {
  913. std::vector<std::string> args = cmExpandedList(compilerLauncher, true);
  914. if (!args.empty()) {
  915. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  916. args[0], cmOutputConverter::SHELL);
  917. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  918. i = this->LocalGenerator->EscapeForShell(i);
  919. }
  920. }
  921. compileCommands.front().insert(0, cmJoin(args, " ") + " ");
  922. }
  923. std::string launcher;
  924. {
  925. cmProp val = this->LocalGenerator->GetRuleLauncher(
  926. this->GeneratorTarget, "RULE_LAUNCH_COMPILE");
  927. if (cmNonempty(val)) {
  928. launcher = cmStrCat(*val, ' ');
  929. }
  930. }
  931. std::string flagsWithDeps(flags);
  932. if (compilerGenerateDeps) {
  933. // Injects dependency computation
  934. auto depFlags = this->Makefile->GetSafeDefinition(
  935. cmStrCat("CMAKE_DEPFILE_FLAGS_", lang));
  936. if (!depFlags.empty()) {
  937. // Add dependency flags
  938. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  939. depFlags, vars);
  940. flagsWithDeps.append(1, ' ');
  941. flagsWithDeps.append(depFlags);
  942. }
  943. vars.Flags = flagsWithDeps.c_str();
  944. const auto& extraCommands = this->Makefile->GetSafeDefinition(
  945. cmStrCat("CMAKE_", lang, "_DEPENDS_EXTRA_COMMANDS"));
  946. if (!extraCommands.empty()) {
  947. auto commandList = cmExpandedList(extraCommands);
  948. compileCommands.insert(compileCommands.end(), commandList.cbegin(),
  949. commandList.cend());
  950. }
  951. const auto& depFormat = this->Makefile->GetRequiredDefinition(
  952. cmStrCat("CMAKE_", lang, "_DEPFILE_FORMAT"));
  953. if (depFormat == "msvc"_s) {
  954. // compiler must be launched through a wrapper to pick-up dependencies
  955. std::string depFilter =
  956. "$(CMAKE_COMMAND) -E cmake_cl_compile_depends ";
  957. depFilter += cmStrCat("--dep-file=", shellDependencyFile);
  958. depFilter +=
  959. cmStrCat(" --working-dir=",
  960. this->LocalGenerator->ConvertToOutputFormat(
  961. this->LocalGenerator->GetCurrentBinaryDirectory(),
  962. cmOutputConverter::SHELL));
  963. const auto& prefix = this->Makefile->GetSafeDefinition(
  964. cmStrCat("CMAKE_", lang, "_CL_SHOWINCLUDES_PREFIX"));
  965. depFilter += cmStrCat(" --filter-prefix=",
  966. this->LocalGenerator->ConvertToOutputFormat(
  967. prefix, cmOutputConverter::SHELL));
  968. depFilter += " -- ";
  969. compileCommands.front().insert(0, depFilter);
  970. }
  971. }
  972. // Expand placeholders in the commands.
  973. for (std::string& compileCommand : compileCommands) {
  974. compileCommand = cmStrCat(launcher, compileCommand);
  975. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  976. compileCommand, vars);
  977. }
  978. // Change the command working directory to the local build tree.
  979. this->LocalGenerator->CreateCDCommand(
  980. compileCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  981. this->LocalGenerator->GetBinaryDirectory());
  982. cm::append(commands, compileCommands);
  983. }
  984. // Check for extra outputs created by the compilation.
  985. std::vector<std::string> outputs(1, relativeObj);
  986. if (cmProp extra_outputs_str = source.GetProperty("OBJECT_OUTPUTS")) {
  987. std::string evaluated_outputs = cmGeneratorExpression::Evaluate(
  988. *extra_outputs_str, this->LocalGenerator, config);
  989. if (!evaluated_outputs.empty()) {
  990. // Register these as extra files to clean.
  991. cmExpandList(evaluated_outputs, outputs);
  992. }
  993. }
  994. if (!ispcHeaderRelative.empty()) {
  995. // can't move ispcHeader as vars is using it
  996. outputs.emplace_back(ispcHeaderRelative);
  997. }
  998. if (outputs.size() > 1) {
  999. this->CleanFiles.insert(outputs.begin() + 1, outputs.end());
  1000. }
  1001. if (compilerGenerateDeps) {
  1002. depends.push_back(dependencyTimestamp);
  1003. }
  1004. // Write the rule.
  1005. this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
  1006. commands);
  1007. if (compilerGenerateDeps) {
  1008. // set back flags without dependency generation
  1009. vars.Flags = flags.c_str();
  1010. }
  1011. bool do_preprocess_rules = lang_has_preprocessor &&
  1012. this->LocalGenerator->GetCreatePreprocessedSourceRules();
  1013. bool do_assembly_rules =
  1014. lang_has_assembly && this->LocalGenerator->GetCreateAssemblySourceRules();
  1015. if (do_preprocess_rules || do_assembly_rules) {
  1016. std::vector<std::string> force_depends;
  1017. force_depends.emplace_back("cmake_force");
  1018. std::string::size_type dot_pos = relativeObj.rfind('.');
  1019. std::string relativeObjBase = relativeObj.substr(0, dot_pos);
  1020. dot_pos = obj.rfind('.');
  1021. std::string objBase = obj.substr(0, dot_pos);
  1022. if (do_preprocess_rules) {
  1023. commands.clear();
  1024. std::string relativeObjI = relativeObjBase + ".i";
  1025. std::string objI = objBase + ".i";
  1026. std::string preprocessEcho =
  1027. cmStrCat("Preprocessing ", lang, " source to ", objI);
  1028. this->LocalGenerator->AppendEcho(
  1029. commands, preprocessEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  1030. std::string preprocessRuleVar =
  1031. cmStrCat("CMAKE_", lang, "_CREATE_PREPROCESSED_SOURCE");
  1032. if (cmProp preprocessRule =
  1033. this->Makefile->GetDefinition(preprocessRuleVar)) {
  1034. std::vector<std::string> preprocessCommands =
  1035. cmExpandedList(*preprocessRule);
  1036. std::string shellObjI = this->LocalGenerator->ConvertToOutputFormat(
  1037. objI, cmOutputConverter::SHELL);
  1038. vars.PreprocessedSource = shellObjI.c_str();
  1039. // Expand placeholders in the commands.
  1040. for (std::string& preprocessCommand : preprocessCommands) {
  1041. // no launcher for preprocessor commands
  1042. rulePlaceholderExpander->ExpandRuleVariables(
  1043. this->LocalGenerator, preprocessCommand, vars);
  1044. }
  1045. this->LocalGenerator->CreateCDCommand(
  1046. preprocessCommands,
  1047. this->LocalGenerator->GetCurrentBinaryDirectory(),
  1048. this->LocalGenerator->GetBinaryDirectory());
  1049. cm::append(commands, preprocessCommands);
  1050. } else {
  1051. std::string cmd =
  1052. cmStrCat("$(CMAKE_COMMAND) -E cmake_unimplemented_variable ",
  1053. preprocessRuleVar);
  1054. commands.push_back(std::move(cmd));
  1055. }
  1056. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1057. relativeObjI, force_depends,
  1058. commands, false);
  1059. }
  1060. if (do_assembly_rules) {
  1061. commands.clear();
  1062. std::string relativeObjS = relativeObjBase + ".s";
  1063. std::string objS = objBase + ".s";
  1064. std::string assemblyEcho =
  1065. cmStrCat("Compiling ", lang, " source to assembly ", objS);
  1066. this->LocalGenerator->AppendEcho(
  1067. commands, assemblyEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  1068. std::string assemblyRuleVar =
  1069. cmStrCat("CMAKE_", lang, "_CREATE_ASSEMBLY_SOURCE");
  1070. if (cmProp assemblyRule =
  1071. this->Makefile->GetDefinition(assemblyRuleVar)) {
  1072. std::vector<std::string> assemblyCommands =
  1073. cmExpandedList(*assemblyRule);
  1074. std::string shellObjS = this->LocalGenerator->ConvertToOutputFormat(
  1075. objS, cmOutputConverter::SHELL);
  1076. vars.AssemblySource = shellObjS.c_str();
  1077. // Expand placeholders in the commands.
  1078. for (std::string& assemblyCommand : assemblyCommands) {
  1079. // no launcher for assembly commands
  1080. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  1081. assemblyCommand, vars);
  1082. }
  1083. this->LocalGenerator->CreateCDCommand(
  1084. assemblyCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  1085. this->LocalGenerator->GetBinaryDirectory());
  1086. cm::append(commands, assemblyCommands);
  1087. } else {
  1088. std::string cmd =
  1089. cmStrCat("$(CMAKE_COMMAND) -E cmake_unimplemented_variable ",
  1090. assemblyRuleVar);
  1091. commands.push_back(std::move(cmd));
  1092. }
  1093. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1094. relativeObjS, force_depends,
  1095. commands, false);
  1096. }
  1097. }
  1098. }
  1099. void cmMakefileTargetGenerator::WriteTargetCleanRules()
  1100. {
  1101. std::vector<std::string> depends;
  1102. std::vector<std::string> commands;
  1103. // Construct the clean target name.
  1104. std::string cleanTarget = cmStrCat(
  1105. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget),
  1106. "/clean");
  1107. // Construct the clean command.
  1108. this->LocalGenerator->AppendCleanCommand(commands, this->CleanFiles,
  1109. this->GeneratorTarget);
  1110. this->LocalGenerator->CreateCDCommand(
  1111. commands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  1112. this->LocalGenerator->GetBinaryDirectory());
  1113. // Write the rule.
  1114. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1115. cleanTarget, depends, commands, true);
  1116. }
  1117. bool cmMakefileTargetGenerator::WriteMakeRule(
  1118. std::ostream& os, const char* comment,
  1119. const std::vector<std::string>& outputs,
  1120. const std::vector<std::string>& depends,
  1121. const std::vector<std::string>& commands, bool in_help)
  1122. {
  1123. bool symbolic = false;
  1124. if (outputs.empty()) {
  1125. return symbolic;
  1126. }
  1127. // Check whether we need to bother checking for a symbolic output.
  1128. bool need_symbolic = this->GlobalGenerator->GetNeedSymbolicMark();
  1129. // Check whether the first output is marked as symbolic.
  1130. if (need_symbolic) {
  1131. if (cmSourceFile* sf = this->Makefile->GetSource(outputs[0])) {
  1132. symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  1133. }
  1134. }
  1135. // We always attach the actual commands to the first output.
  1136. this->LocalGenerator->WriteMakeRule(os, comment, outputs[0], depends,
  1137. commands, symbolic, in_help);
  1138. // For single outputs, we are done.
  1139. if (outputs.size() == 1) {
  1140. return symbolic;
  1141. }
  1142. // For multiple outputs, make the extra ones depend on the first one.
  1143. std::vector<std::string> const output_depends(1, outputs[0]);
  1144. for (std::string const& output : cmMakeRange(outputs).advance(1)) {
  1145. // Touch the extra output so "make" knows that it was updated,
  1146. // but only if the output was actually created.
  1147. std::string const out = this->LocalGenerator->ConvertToOutputFormat(
  1148. this->LocalGenerator->MaybeRelativeToTopBinDir(output),
  1149. cmOutputConverter::SHELL);
  1150. std::vector<std::string> output_commands;
  1151. bool o_symbolic = false;
  1152. if (need_symbolic) {
  1153. if (cmSourceFile* sf = this->Makefile->GetSource(output)) {
  1154. o_symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  1155. }
  1156. }
  1157. symbolic = symbolic && o_symbolic;
  1158. if (!o_symbolic) {
  1159. output_commands.push_back("@$(CMAKE_COMMAND) -E touch_nocreate " + out);
  1160. }
  1161. this->LocalGenerator->WriteMakeRule(os, nullptr, output, output_depends,
  1162. output_commands, o_symbolic, in_help);
  1163. if (!o_symbolic) {
  1164. // At build time, remove the first output if this one does not exist
  1165. // so that "make" will rerun the real commands that create this one.
  1166. MultipleOutputPairsType::value_type p(output, outputs[0]);
  1167. this->MultipleOutputPairs.insert(p);
  1168. }
  1169. }
  1170. return symbolic;
  1171. }
  1172. void cmMakefileTargetGenerator::WriteTargetDependRules()
  1173. {
  1174. // must write the targets depend info file
  1175. std::string dir =
  1176. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  1177. this->InfoFileNameFull = cmStrCat(dir, "/DependInfo.cmake");
  1178. this->InfoFileNameFull =
  1179. this->LocalGenerator->ConvertToFullPath(this->InfoFileNameFull);
  1180. this->InfoFileStream =
  1181. cm::make_unique<cmGeneratedFileStream>(this->InfoFileNameFull);
  1182. if (!this->InfoFileStream) {
  1183. return;
  1184. }
  1185. this->InfoFileStream->SetCopyIfDifferent(true);
  1186. this->LocalGenerator->WriteDependLanguageInfo(*this->InfoFileStream,
  1187. this->GeneratorTarget);
  1188. // Store multiple output pairs in the depend info file.
  1189. if (!this->MultipleOutputPairs.empty()) {
  1190. /* clang-format off */
  1191. *this->InfoFileStream
  1192. << "\n"
  1193. << "# Pairs of files generated by the same build rule.\n"
  1194. << "set(CMAKE_MULTIPLE_OUTPUT_PAIRS\n";
  1195. /* clang-format on */
  1196. for (auto const& pi : this->MultipleOutputPairs) {
  1197. *this->InfoFileStream
  1198. << " " << cmOutputConverter::EscapeForCMake(pi.first) << " "
  1199. << cmOutputConverter::EscapeForCMake(pi.second) << "\n";
  1200. }
  1201. *this->InfoFileStream << " )\n\n";
  1202. }
  1203. // Store list of targets linked directly or transitively.
  1204. {
  1205. /* clang-format off */
  1206. *this->InfoFileStream
  1207. << "\n"
  1208. << "# Targets to which this target links.\n"
  1209. << "set(CMAKE_TARGET_LINKED_INFO_FILES\n";
  1210. /* clang-format on */
  1211. std::vector<std::string> dirs =
  1212. this->GetLinkedTargetDirectories(this->GetConfigName());
  1213. for (std::string const& d : dirs) {
  1214. *this->InfoFileStream << " \"" << d << "/DependInfo.cmake\"\n";
  1215. }
  1216. *this->InfoFileStream << " )\n";
  1217. }
  1218. std::string const& working_dir =
  1219. this->LocalGenerator->GetCurrentBinaryDirectory();
  1220. /* clang-format off */
  1221. *this->InfoFileStream
  1222. << "\n"
  1223. << "# Fortran module output directory.\n"
  1224. << "set(CMAKE_Fortran_TARGET_MODULE_DIR \""
  1225. << this->GeneratorTarget->GetFortranModuleDirectory(working_dir)
  1226. << "\")\n";
  1227. /* clang-format on */
  1228. // and now write the rule to use it
  1229. std::vector<std::string> depends;
  1230. std::vector<std::string> commands;
  1231. // Construct the name of the dependency generation target.
  1232. std::string depTarget = cmStrCat(
  1233. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget),
  1234. "/depend");
  1235. // Add a command to call CMake to scan dependencies. CMake will
  1236. // touch the corresponding depends file after scanning dependencies.
  1237. std::ostringstream depCmd;
  1238. // TODO: Account for source file properties and directory-level
  1239. // definitions when scanning for dependencies.
  1240. #if !defined(_WIN32) || defined(__CYGWIN__)
  1241. // This platform supports symlinks, so cmSystemTools will translate
  1242. // paths. Make sure PWD is set to the original name of the home
  1243. // output directory to help cmSystemTools to create the same
  1244. // translation table for the dependency scanning process.
  1245. depCmd << "cd "
  1246. << (this->LocalGenerator->ConvertToOutputFormat(
  1247. this->LocalGenerator->GetBinaryDirectory(),
  1248. cmOutputConverter::SHELL))
  1249. << " && ";
  1250. #endif
  1251. // Generate a call this signature:
  1252. //
  1253. // cmake -E cmake_depends <generator>
  1254. // <home-src-dir> <start-src-dir>
  1255. // <home-out-dir> <start-out-dir>
  1256. // <dep-info> --color=$(COLOR)
  1257. //
  1258. // This gives the dependency scanner enough information to recreate
  1259. // the state of our local generator sufficiently for its needs.
  1260. depCmd << "$(CMAKE_COMMAND) -E cmake_depends \""
  1261. << this->GlobalGenerator->GetName() << "\" "
  1262. << this->LocalGenerator->ConvertToOutputFormat(
  1263. this->LocalGenerator->GetSourceDirectory(),
  1264. cmOutputConverter::SHELL)
  1265. << " "
  1266. << this->LocalGenerator->ConvertToOutputFormat(
  1267. this->LocalGenerator->GetCurrentSourceDirectory(),
  1268. cmOutputConverter::SHELL)
  1269. << " "
  1270. << this->LocalGenerator->ConvertToOutputFormat(
  1271. this->LocalGenerator->GetBinaryDirectory(),
  1272. cmOutputConverter::SHELL)
  1273. << " "
  1274. << this->LocalGenerator->ConvertToOutputFormat(
  1275. this->LocalGenerator->GetCurrentBinaryDirectory(),
  1276. cmOutputConverter::SHELL)
  1277. << " "
  1278. << this->LocalGenerator->ConvertToOutputFormat(
  1279. cmSystemTools::CollapseFullPath(this->InfoFileNameFull),
  1280. cmOutputConverter::SHELL);
  1281. if (this->LocalGenerator->GetColorMakefile()) {
  1282. depCmd << " --color=$(COLOR)";
  1283. }
  1284. commands.push_back(depCmd.str());
  1285. // Make sure all custom command outputs in this target are built.
  1286. if (this->CustomCommandDriver == OnDepends) {
  1287. this->DriveCustomCommands(depends);
  1288. }
  1289. // Write the rule.
  1290. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1291. depTarget, depends, commands, true);
  1292. }
  1293. void cmMakefileTargetGenerator::DriveCustomCommands(
  1294. std::vector<std::string>& depends)
  1295. {
  1296. // Depend on all custom command outputs.
  1297. cm::append(depends, this->CustomCommandOutputs);
  1298. }
  1299. void cmMakefileTargetGenerator::WriteObjectDependRules(
  1300. cmSourceFile const& source, std::vector<std::string>& depends)
  1301. {
  1302. // Create the list of dependencies known at cmake time. These are
  1303. // shared between the object file and dependency scanning rule.
  1304. depends.push_back(source.GetFullPath());
  1305. if (cmProp objectDeps = source.GetProperty("OBJECT_DEPENDS")) {
  1306. cmExpandList(*objectDeps, depends);
  1307. }
  1308. }
  1309. void cmMakefileTargetGenerator::WriteDeviceLinkRule(
  1310. std::vector<std::string>& commands, const std::string& output)
  1311. {
  1312. std::string architecturesStr =
  1313. this->GeneratorTarget->GetSafeProperty("CUDA_ARCHITECTURES");
  1314. if (cmIsOff(architecturesStr)) {
  1315. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  1316. "CUDA_SEPARABLE_COMPILATION on Clang "
  1317. "requires CUDA_ARCHITECTURES to be set.");
  1318. return;
  1319. }
  1320. std::vector<std::string> architectures = cmExpandedList(architecturesStr);
  1321. // Ensure there are no duplicates.
  1322. const std::vector<std::string> linkDeps = [&]() -> std::vector<std::string> {
  1323. std::vector<std::string> deps;
  1324. this->AppendTargetDepends(deps, true);
  1325. this->GeneratorTarget->GetLinkDepends(deps, this->GetConfigName(), "CUDA");
  1326. std::copy(this->Objects.begin(), this->Objects.end(),
  1327. std::back_inserter(deps));
  1328. std::unordered_set<std::string> depsSet(deps.begin(), deps.end());
  1329. deps.clear();
  1330. std::copy(depsSet.begin(), depsSet.end(), std::back_inserter(deps));
  1331. return deps;
  1332. }();
  1333. const std::string objectDir = this->GeneratorTarget->ObjectDirectory;
  1334. const std::string relObjectDir =
  1335. this->LocalGenerator->MaybeRelativeToCurBinDir(objectDir);
  1336. // Construct a list of files associated with this executable that
  1337. // may need to be cleaned.
  1338. std::vector<std::string> cleanFiles;
  1339. cleanFiles.push_back(this->LocalGenerator->MaybeRelativeToCurBinDir(output));
  1340. std::string profiles;
  1341. std::vector<std::string> fatbinaryDepends;
  1342. std::string registerFile = cmStrCat(objectDir, "cmake_cuda_register.h");
  1343. // Link device code for each architecture.
  1344. for (const std::string& architectureKind : architectures) {
  1345. // Clang always generates real code, so strip the specifier.
  1346. const std::string architecture =
  1347. architectureKind.substr(0, architectureKind.find('-'));
  1348. const std::string cubin =
  1349. cmStrCat(relObjectDir, "sm_", architecture, ".cubin");
  1350. profiles += cmStrCat(" -im=profile=sm_", architecture, ",file=", cubin);
  1351. fatbinaryDepends.emplace_back(cubin);
  1352. std::string registerFileCmd;
  1353. // The generated register file contains macros that when expanded
  1354. // register the device routines. Because the routines are the same for
  1355. // all architectures the register file will be the same too. Thus
  1356. // generate it only on the first invocation to reduce overhead.
  1357. if (fatbinaryDepends.size() == 1) {
  1358. std::string registerFileRel =
  1359. this->LocalGenerator->MaybeRelativeToCurBinDir(registerFile);
  1360. registerFileCmd =
  1361. cmStrCat(" --register-link-binaries=", registerFileRel);
  1362. cleanFiles.push_back(registerFileRel);
  1363. }
  1364. std::string command = cmStrCat(
  1365. this->Makefile->GetRequiredDefinition("CMAKE_CUDA_DEVICE_LINKER"),
  1366. " -arch=sm_", architecture, registerFileCmd, " -o=$@ ",
  1367. cmJoin(linkDeps, " "));
  1368. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr, cubin,
  1369. linkDeps, { command }, false);
  1370. }
  1371. // Combine all architectures into a single fatbinary.
  1372. const std::string fatbinaryCommand =
  1373. cmStrCat(this->Makefile->GetRequiredDefinition("CMAKE_CUDA_FATBINARY"),
  1374. " -64 -cmdline=--compile-only -compress-all -link "
  1375. "--embedded-fatbin=$@",
  1376. profiles);
  1377. const std::string fatbinaryOutput =
  1378. cmStrCat(objectDir, "cmake_cuda_fatbin.h");
  1379. const std::string fatbinaryOutputRel =
  1380. this->LocalGenerator->MaybeRelativeToCurBinDir(fatbinaryOutput);
  1381. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1382. fatbinaryOutputRel, fatbinaryDepends,
  1383. { fatbinaryCommand }, false);
  1384. // Compile the stub that registers the kernels and contains the
  1385. // fatbinaries.
  1386. cmRulePlaceholderExpander::RuleVariables vars;
  1387. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  1388. vars.CMTargetType =
  1389. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  1390. vars.Language = "CUDA";
  1391. vars.Object = output.c_str();
  1392. vars.Fatbinary = fatbinaryOutput.c_str();
  1393. vars.RegisterFile = registerFile.c_str();
  1394. std::string flags = this->GetFlags("CUDA", this->GetConfigName());
  1395. vars.Flags = flags.c_str();
  1396. std::string compileCmd = this->GetLinkRule("CMAKE_CUDA_DEVICE_LINK_COMPILE");
  1397. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  1398. this->LocalGenerator->CreateRulePlaceholderExpander());
  1399. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  1400. compileCmd, vars);
  1401. commands.emplace_back(compileCmd);
  1402. this->LocalGenerator->WriteMakeRule(
  1403. *this->BuildFileStream, nullptr, output,
  1404. { cmStrCat(relObjectDir, "cmake_cuda_fatbin.h") }, commands, false);
  1405. // Clean all the possible executable names and symlinks.
  1406. this->CleanFiles.insert(cleanFiles.begin(), cleanFiles.end());
  1407. }
  1408. void cmMakefileTargetGenerator::GenerateCustomRuleFile(
  1409. cmCustomCommandGenerator const& ccg)
  1410. {
  1411. // Collect the commands.
  1412. std::vector<std::string> commands;
  1413. std::string comment = this->LocalGenerator->ConstructComment(ccg);
  1414. if (!comment.empty()) {
  1415. // add in a progress call if needed
  1416. this->NumberOfProgressActions++;
  1417. if (!this->NoRuleMessages) {
  1418. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  1419. this->MakeEchoProgress(progress);
  1420. this->LocalGenerator->AppendEcho(
  1421. commands, comment, cmLocalUnixMakefileGenerator3::EchoGenerate,
  1422. &progress);
  1423. }
  1424. }
  1425. // Now append the actual user-specified commands.
  1426. std::ostringstream content;
  1427. this->LocalGenerator->AppendCustomCommand(
  1428. commands, ccg, this->GeneratorTarget,
  1429. this->LocalGenerator->GetBinaryDirectory(), false, &content);
  1430. // Collect the dependencies.
  1431. std::vector<std::string> depends;
  1432. this->LocalGenerator->AppendCustomDepend(depends, ccg);
  1433. if (!ccg.GetCC().GetDepfile().empty()) {
  1434. // Add dependency over timestamp file for dependencies management
  1435. auto dependTimestamp = cmSystemTools::ConvertToOutputPath(
  1436. this->LocalGenerator->MaybeRelativeToTopBinDir(
  1437. cmStrCat(this->TargetBuildDirectoryFull, "/compiler_depend.ts")));
  1438. depends.push_back(dependTimestamp);
  1439. }
  1440. // Write the rule.
  1441. const std::vector<std::string>& outputs = ccg.GetOutputs();
  1442. bool symbolic = this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs,
  1443. depends, commands);
  1444. // Symbolic inputs are not expected to exist, so add dummy rules.
  1445. if (this->CMP0113New && !depends.empty()) {
  1446. std::vector<std::string> no_depends;
  1447. std::vector<std::string> no_commands;
  1448. for (std::string const& dep : depends) {
  1449. if (cmSourceFile* dsf =
  1450. this->Makefile->GetSource(dep, cmSourceFileLocationKind::Known)) {
  1451. if (dsf->GetPropertyAsBool("SYMBOLIC")) {
  1452. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1453. dep, no_depends, no_commands,
  1454. true);
  1455. }
  1456. }
  1457. }
  1458. }
  1459. // If the rule has changed make sure the output is rebuilt.
  1460. if (!symbolic) {
  1461. this->GlobalGenerator->AddRuleHash(ccg.GetOutputs(), content.str());
  1462. }
  1463. // Setup implicit dependency scanning.
  1464. for (auto const& idi : ccg.GetCC().GetImplicitDepends()) {
  1465. std::string objFullPath = cmSystemTools::CollapseFullPath(
  1466. outputs[0], this->LocalGenerator->GetCurrentBinaryDirectory());
  1467. std::string srcFullPath = cmSystemTools::CollapseFullPath(
  1468. idi.second, this->LocalGenerator->GetCurrentBinaryDirectory());
  1469. this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, idi.first,
  1470. objFullPath, srcFullPath);
  1471. }
  1472. // Setup implicit depend for depfile if any
  1473. if (!ccg.GetCC().GetDepfile().empty()) {
  1474. std::string objFullPath = cmSystemTools::CollapseFullPath(
  1475. outputs[0], this->LocalGenerator->GetCurrentBinaryDirectory());
  1476. this->LocalGenerator->AddImplicitDepends(
  1477. this->GeneratorTarget, "CUSTOM", objFullPath, ccg.GetFullDepfile(),
  1478. cmDependencyScannerKind::Compiler);
  1479. }
  1480. this->CustomCommandOutputs.insert(outputs.begin(), outputs.end());
  1481. }
  1482. void cmMakefileTargetGenerator::MakeEchoProgress(
  1483. cmLocalUnixMakefileGenerator3::EchoProgress& progress) const
  1484. {
  1485. progress.Dir =
  1486. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), "/CMakeFiles");
  1487. std::ostringstream progressArg;
  1488. progressArg << "$(CMAKE_PROGRESS_" << this->NumberOfProgressActions << ")";
  1489. progress.Arg = progressArg.str();
  1490. }
  1491. void cmMakefileTargetGenerator::WriteObjectsVariable(
  1492. std::string& variableName, std::string& variableNameExternal,
  1493. bool useWatcomQuote)
  1494. {
  1495. // Write a make variable assignment that lists all objects for the
  1496. // target.
  1497. variableName = this->LocalGenerator->CreateMakeVariable(
  1498. this->GeneratorTarget->GetName(), "_OBJECTS");
  1499. *this->BuildFileStream << "# Object files for target "
  1500. << this->GeneratorTarget->GetName() << "\n"
  1501. << variableName << " =";
  1502. std::string object;
  1503. const auto& lineContinue = this->GlobalGenerator->LineContinueDirective;
  1504. cmProp pchExtension = this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  1505. for (std::string const& obj : this->Objects) {
  1506. if (cmSystemTools::StringEndsWith(obj, cmToCStr(pchExtension))) {
  1507. continue;
  1508. }
  1509. *this->BuildFileStream << " " << lineContinue;
  1510. *this->BuildFileStream
  1511. << cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1512. obj, useWatcomQuote);
  1513. }
  1514. *this->BuildFileStream << "\n";
  1515. // Write a make variable assignment that lists all external objects
  1516. // for the target.
  1517. variableNameExternal = this->LocalGenerator->CreateMakeVariable(
  1518. this->GeneratorTarget->GetName(), "_EXTERNAL_OBJECTS");
  1519. /* clang-format off */
  1520. *this->BuildFileStream
  1521. << "\n"
  1522. << "# External object files for target "
  1523. << this->GeneratorTarget->GetName() << "\n"
  1524. << variableNameExternal << " =";
  1525. /* clang-format on */
  1526. for (std::string const& obj : this->ExternalObjects) {
  1527. object = this->LocalGenerator->MaybeRelativeToCurBinDir(obj);
  1528. *this->BuildFileStream << " " << lineContinue;
  1529. *this->BuildFileStream
  1530. << cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1531. obj, useWatcomQuote);
  1532. }
  1533. *this->BuildFileStream << "\n"
  1534. << "\n";
  1535. }
  1536. class cmMakefileTargetGeneratorObjectStrings
  1537. {
  1538. public:
  1539. cmMakefileTargetGeneratorObjectStrings(std::vector<std::string>& strings,
  1540. cmOutputConverter* outputConverter,
  1541. cmStateDirectory const& stateDir,
  1542. std::string::size_type limit)
  1543. : Strings(strings)
  1544. , OutputConverter(outputConverter)
  1545. , StateDir(stateDir)
  1546. , LengthLimit(limit)
  1547. {
  1548. this->Space = "";
  1549. }
  1550. void Feed(std::string const& obj)
  1551. {
  1552. // Construct the name of the next object.
  1553. this->NextObject = this->OutputConverter->ConvertToOutputFormat(
  1554. this->OutputConverter->MaybeRelativeToCurBinDir(obj),
  1555. cmOutputConverter::RESPONSE);
  1556. // Roll over to next string if the limit will be exceeded.
  1557. if (this->LengthLimit != std::string::npos &&
  1558. (this->CurrentString.length() + 1 + this->NextObject.length() >
  1559. this->LengthLimit)) {
  1560. this->Strings.push_back(this->CurrentString);
  1561. this->CurrentString.clear();
  1562. this->Space = "";
  1563. }
  1564. // Separate from previous object.
  1565. this->CurrentString += this->Space;
  1566. this->Space = " ";
  1567. // Append this object.
  1568. this->CurrentString += this->NextObject;
  1569. }
  1570. void Done() { this->Strings.push_back(this->CurrentString); }
  1571. private:
  1572. std::vector<std::string>& Strings;
  1573. cmOutputConverter* OutputConverter;
  1574. cmStateDirectory StateDir;
  1575. std::string::size_type LengthLimit;
  1576. std::string CurrentString;
  1577. std::string NextObject;
  1578. const char* Space;
  1579. };
  1580. void cmMakefileTargetGenerator::WriteObjectsStrings(
  1581. std::vector<std::string>& objStrings, std::string::size_type limit)
  1582. {
  1583. cmProp pchExtension = this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  1584. cmMakefileTargetGeneratorObjectStrings helper(
  1585. objStrings, this->LocalGenerator,
  1586. this->LocalGenerator->GetStateSnapshot().GetDirectory(), limit);
  1587. for (std::string const& obj : this->Objects) {
  1588. if (cmSystemTools::StringEndsWith(obj, cmToCStr(pchExtension))) {
  1589. continue;
  1590. }
  1591. helper.Feed(obj);
  1592. }
  1593. for (std::string const& obj : this->ExternalObjects) {
  1594. helper.Feed(obj);
  1595. }
  1596. auto ispcAdditionalObjs =
  1597. this->GeneratorTarget->GetGeneratedISPCObjects(this->GetConfigName());
  1598. for (std::string const& obj : ispcAdditionalObjs) {
  1599. helper.Feed(obj);
  1600. }
  1601. helper.Done();
  1602. }
  1603. void cmMakefileTargetGenerator::WriteTargetDriverRule(
  1604. const std::string& main_output, bool relink)
  1605. {
  1606. // Compute the name of the driver target.
  1607. std::string dir =
  1608. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget);
  1609. std::string buildTargetRuleName =
  1610. cmStrCat(dir, relink ? "/preinstall" : "/build");
  1611. buildTargetRuleName =
  1612. this->LocalGenerator->MaybeRelativeToTopBinDir(buildTargetRuleName);
  1613. // Build the list of target outputs to drive.
  1614. std::vector<std::string> depends;
  1615. depends.push_back(main_output);
  1616. const char* comment = nullptr;
  1617. if (relink) {
  1618. // Setup the comment for the preinstall driver.
  1619. comment = "Rule to relink during preinstall.";
  1620. } else {
  1621. // Setup the comment for the main build driver.
  1622. comment = "Rule to build all files generated by this target.";
  1623. // Make sure all custom command outputs in this target are built.
  1624. if (this->CustomCommandDriver == OnBuild) {
  1625. this->DriveCustomCommands(depends);
  1626. }
  1627. // Make sure the extra files are built.
  1628. cm::append(depends, this->ExtraFiles);
  1629. }
  1630. // Write the driver rule.
  1631. std::vector<std::string> no_commands;
  1632. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, comment,
  1633. buildTargetRuleName, depends,
  1634. no_commands, true);
  1635. }
  1636. void cmMakefileTargetGenerator::AppendTargetDepends(
  1637. std::vector<std::string>& depends, bool ignoreType)
  1638. {
  1639. // Static libraries never depend on anything for linking.
  1640. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY &&
  1641. !ignoreType) {
  1642. return;
  1643. }
  1644. // Loop over all library dependencies.
  1645. const std::string& cfg = this->GetConfigName();
  1646. if (cmComputeLinkInformation* cli =
  1647. this->GeneratorTarget->GetLinkInformation(cfg)) {
  1648. cm::append(depends, cli->GetDepends());
  1649. }
  1650. }
  1651. void cmMakefileTargetGenerator::AppendObjectDepends(
  1652. std::vector<std::string>& depends)
  1653. {
  1654. // Add dependencies on the compiled object files.
  1655. std::string const& relPath =
  1656. this->LocalGenerator->GetHomeRelativeOutputPath();
  1657. for (std::string const& obj : this->Objects) {
  1658. std::string objTarget = cmStrCat(relPath, obj);
  1659. depends.push_back(std::move(objTarget));
  1660. }
  1661. // Add dependencies on the external object files.
  1662. cm::append(depends, this->ExternalObjects);
  1663. // Add a dependency on the rule file itself.
  1664. this->LocalGenerator->AppendRuleDepend(depends,
  1665. this->BuildFileNameFull.c_str());
  1666. }
  1667. void cmMakefileTargetGenerator::AppendLinkDepends(
  1668. std::vector<std::string>& depends, const std::string& linkLanguage)
  1669. {
  1670. this->AppendObjectDepends(depends);
  1671. // Add dependencies on targets that must be built first.
  1672. this->AppendTargetDepends(depends);
  1673. // Add a dependency on the link definitions file, if any.
  1674. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1675. this->GeneratorTarget->GetModuleDefinitionInfo(
  1676. this->GetConfigName())) {
  1677. for (cmSourceFile const* src : mdi->Sources) {
  1678. depends.push_back(src->GetFullPath());
  1679. }
  1680. }
  1681. // Add a dependency on user-specified manifest files, if any.
  1682. std::vector<cmSourceFile const*> manifest_srcs;
  1683. this->GeneratorTarget->GetManifests(manifest_srcs, this->GetConfigName());
  1684. for (cmSourceFile const* manifest_src : manifest_srcs) {
  1685. depends.push_back(manifest_src->GetFullPath());
  1686. }
  1687. // Add user-specified dependencies.
  1688. this->GeneratorTarget->GetLinkDepends(depends, this->GetConfigName(),
  1689. linkLanguage);
  1690. }
  1691. std::string cmMakefileTargetGenerator::GetLinkRule(
  1692. const std::string& linkRuleVar)
  1693. {
  1694. std::string linkRule = this->Makefile->GetRequiredDefinition(linkRuleVar);
  1695. if (this->GeneratorTarget->HasImplibGNUtoMS(this->GetConfigName())) {
  1696. std::string ruleVar =
  1697. cmStrCat("CMAKE_",
  1698. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName()),
  1699. "_GNUtoMS_RULE");
  1700. if (cmProp rule = this->Makefile->GetDefinition(ruleVar)) {
  1701. linkRule += *rule;
  1702. }
  1703. }
  1704. return linkRule;
  1705. }
  1706. void cmMakefileTargetGenerator::CloseFileStreams()
  1707. {
  1708. this->BuildFileStream.reset();
  1709. this->InfoFileStream.reset();
  1710. this->FlagFileStream.reset();
  1711. }
  1712. void cmMakefileTargetGenerator::CreateLinkScript(
  1713. const char* name, std::vector<std::string> const& link_commands,
  1714. std::vector<std::string>& makefile_commands,
  1715. std::vector<std::string>& makefile_depends)
  1716. {
  1717. // Create the link script file.
  1718. std::string linkScriptName =
  1719. cmStrCat(this->TargetBuildDirectoryFull, '/', name);
  1720. cmGeneratedFileStream linkScriptStream(linkScriptName);
  1721. linkScriptStream.SetCopyIfDifferent(true);
  1722. for (std::string const& link_command : link_commands) {
  1723. // Do not write out empty commands or commands beginning in the
  1724. // shell no-op ":".
  1725. if (!link_command.empty() && link_command[0] != ':') {
  1726. linkScriptStream << link_command << "\n";
  1727. }
  1728. }
  1729. // Create the makefile command to invoke the link script.
  1730. std::string link_command =
  1731. cmStrCat("$(CMAKE_COMMAND) -E cmake_link_script ",
  1732. this->LocalGenerator->ConvertToOutputFormat(
  1733. this->LocalGenerator->MaybeRelativeToCurBinDir(linkScriptName),
  1734. cmOutputConverter::SHELL),
  1735. " --verbose=$(VERBOSE)");
  1736. makefile_commands.push_back(std::move(link_command));
  1737. makefile_depends.push_back(std::move(linkScriptName));
  1738. }
  1739. bool cmMakefileTargetGenerator::CheckUseResponseFileForObjects(
  1740. std::string const& l) const
  1741. {
  1742. // Check for an explicit setting one way or the other.
  1743. std::string const responseVar =
  1744. "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_OBJECTS";
  1745. if (cmProp val = this->Makefile->GetDefinition(responseVar)) {
  1746. if (!val->empty()) {
  1747. return cmIsOn(val);
  1748. }
  1749. }
  1750. // Check for a system limit.
  1751. if (size_t const limit = cmSystemTools::CalculateCommandLineLengthLimit()) {
  1752. // Compute the total length of our list of object files with room
  1753. // for argument separation and quoting. This does not convert paths
  1754. // relative to CMAKE_CURRENT_BINARY_DIR like the final list will be, so
  1755. // the actual list will likely be much shorter than this. However, in
  1756. // the worst case all objects will remain as absolute paths.
  1757. size_t length = 0;
  1758. for (std::string const& obj : this->Objects) {
  1759. length += obj.size() + 3;
  1760. }
  1761. for (std::string const& ext_obj : this->ExternalObjects) {
  1762. length += ext_obj.size() + 3;
  1763. }
  1764. // We need to guarantee room for both objects and libraries, so
  1765. // if the objects take up more than half then use a response file
  1766. // for them.
  1767. if (length > (limit / 2)) {
  1768. return true;
  1769. }
  1770. }
  1771. // We do not need a response file for objects.
  1772. return false;
  1773. }
  1774. bool cmMakefileTargetGenerator::CheckUseResponseFileForLibraries(
  1775. std::string const& l) const
  1776. {
  1777. // Check for an explicit setting one way or the other.
  1778. std::string const responseVar =
  1779. "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_LIBRARIES";
  1780. if (cmProp val = this->Makefile->GetDefinition(responseVar)) {
  1781. if (!val->empty()) {
  1782. return cmIsOn(val);
  1783. }
  1784. }
  1785. // We do not need a response file for libraries.
  1786. return false;
  1787. }
  1788. std::string cmMakefileTargetGenerator::CreateResponseFile(
  1789. const char* name, std::string const& options,
  1790. std::vector<std::string>& makefile_depends)
  1791. {
  1792. // Create the response file.
  1793. std::string responseFileNameFull =
  1794. cmStrCat(this->TargetBuildDirectoryFull, '/', name);
  1795. cmGeneratedFileStream responseStream(
  1796. responseFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
  1797. responseStream.SetCopyIfDifferent(true);
  1798. responseStream << options << "\n";
  1799. // Add a dependency so the target will rebuild when the set of
  1800. // objects changes.
  1801. makefile_depends.push_back(std::move(responseFileNameFull));
  1802. // Construct the name to be used on the command line.
  1803. std::string responseFileName =
  1804. cmStrCat(this->TargetBuildDirectory, '/', name);
  1805. return responseFileName;
  1806. }
  1807. std::unique_ptr<cmLinkLineComputer>
  1808. cmMakefileTargetGenerator::CreateLinkLineComputer(
  1809. cmOutputConverter* outputConverter, cmStateDirectory const& stateDir)
  1810. {
  1811. if (this->Makefile->IsOn("MSVC60")) {
  1812. return this->GlobalGenerator->CreateMSVC60LinkLineComputer(outputConverter,
  1813. stateDir);
  1814. }
  1815. return this->GlobalGenerator->CreateLinkLineComputer(outputConverter,
  1816. stateDir);
  1817. }
  1818. void cmMakefileTargetGenerator::CreateLinkLibs(
  1819. cmLinkLineComputer* linkLineComputer, std::string& linkLibs,
  1820. bool useResponseFile, std::vector<std::string>& makefile_depends)
  1821. {
  1822. std::string frameworkPath;
  1823. std::string linkPath;
  1824. cmComputeLinkInformation* pcli =
  1825. this->GeneratorTarget->GetLinkInformation(this->GetConfigName());
  1826. this->LocalGenerator->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1827. frameworkPath, linkPath);
  1828. linkLibs = frameworkPath + linkPath + linkLibs;
  1829. if (useResponseFile &&
  1830. linkLibs.find_first_not_of(' ') != std::string::npos) {
  1831. // Lookup the response file reference flag.
  1832. std::string responseFlagVar =
  1833. cmStrCat("CMAKE_",
  1834. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName()),
  1835. "_RESPONSE_FILE_LINK_FLAG");
  1836. std::string responseFlag;
  1837. if (cmProp p = this->Makefile->GetDefinition(responseFlagVar)) {
  1838. responseFlag = *p;
  1839. } else {
  1840. responseFlag = "@";
  1841. }
  1842. // Create this response file.
  1843. std::string link_rsp =
  1844. this->CreateResponseFile("linklibs.rsp", linkLibs, makefile_depends);
  1845. // Reference the response file.
  1846. linkLibs = cmStrCat(responseFlag,
  1847. this->LocalGenerator->ConvertToOutputFormat(
  1848. link_rsp, cmOutputConverter::SHELL));
  1849. }
  1850. }
  1851. void cmMakefileTargetGenerator::CreateObjectLists(
  1852. bool useLinkScript, bool useArchiveRules, bool useResponseFile,
  1853. std::string& buildObjs, std::vector<std::string>& makefile_depends,
  1854. bool useWatcomQuote)
  1855. {
  1856. std::string variableName;
  1857. std::string variableNameExternal;
  1858. this->WriteObjectsVariable(variableName, variableNameExternal,
  1859. useWatcomQuote);
  1860. if (useResponseFile) {
  1861. // MSVC response files cannot exceed 128K.
  1862. std::string::size_type const responseFileLimit = 131000;
  1863. // Construct the individual object list strings.
  1864. std::vector<std::string> object_strings;
  1865. this->WriteObjectsStrings(object_strings, responseFileLimit);
  1866. // Lookup the response file reference flag.
  1867. std::string responseFlagVar =
  1868. cmStrCat("CMAKE_",
  1869. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName()),
  1870. "_RESPONSE_FILE_LINK_FLAG");
  1871. std::string responseFlag;
  1872. if (cmProp p = this->Makefile->GetDefinition(responseFlagVar)) {
  1873. responseFlag = *p;
  1874. } else {
  1875. responseFlag = "@";
  1876. }
  1877. // Write a response file for each string.
  1878. const char* sep = "";
  1879. for (unsigned int i = 0; i < object_strings.size(); ++i) {
  1880. // Number the response files.
  1881. char rsp[32];
  1882. sprintf(rsp, "objects%u.rsp", i + 1);
  1883. // Create this response file.
  1884. std::string objects_rsp =
  1885. this->CreateResponseFile(rsp, object_strings[i], makefile_depends);
  1886. // Separate from previous response file references.
  1887. buildObjs += sep;
  1888. sep = " ";
  1889. // Reference the response file.
  1890. buildObjs += responseFlag;
  1891. buildObjs += this->LocalGenerator->ConvertToOutputFormat(
  1892. objects_rsp, cmOutputConverter::SHELL);
  1893. }
  1894. } else if (useLinkScript) {
  1895. if (!useArchiveRules) {
  1896. std::vector<std::string> objStrings;
  1897. this->WriteObjectsStrings(objStrings);
  1898. buildObjs = objStrings[0];
  1899. }
  1900. } else {
  1901. buildObjs =
  1902. cmStrCat("$(", variableName, ") $(", variableNameExternal, ')');
  1903. }
  1904. }
  1905. void cmMakefileTargetGenerator::AddIncludeFlags(std::string& flags,
  1906. const std::string& lang,
  1907. const std::string& /*config*/)
  1908. {
  1909. std::string responseVar =
  1910. cmStrCat("CMAKE_", lang, "_USE_RESPONSE_FILE_FOR_INCLUDES");
  1911. bool useResponseFile = this->Makefile->IsOn(responseVar);
  1912. std::vector<std::string> includes;
  1913. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1914. lang, this->GetConfigName());
  1915. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  1916. includes, this->GeneratorTarget, lang, this->GetConfigName(),
  1917. useResponseFile);
  1918. if (includeFlags.empty()) {
  1919. return;
  1920. }
  1921. if (useResponseFile) {
  1922. std::string const responseFlagVar =
  1923. "CMAKE_" + lang + "_RESPONSE_FILE_FLAG";
  1924. std::string responseFlag =
  1925. this->Makefile->GetSafeDefinition(responseFlagVar);
  1926. if (responseFlag.empty()) {
  1927. responseFlag = "@";
  1928. }
  1929. std::string name = cmStrCat("includes_", lang, ".rsp");
  1930. std::string arg = std::move(responseFlag) +
  1931. this->CreateResponseFile(name.c_str(), includeFlags,
  1932. this->FlagFileDepends[lang]);
  1933. this->LocalGenerator->AppendFlags(flags, arg);
  1934. } else {
  1935. this->LocalGenerator->AppendFlags(flags, includeFlags);
  1936. }
  1937. }
  1938. void cmMakefileTargetGenerator::GenDefFile(
  1939. std::vector<std::string>& real_link_commands)
  1940. {
  1941. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1942. this->GeneratorTarget->GetModuleDefinitionInfo(this->GetConfigName());
  1943. if (!mdi || !mdi->DefFileGenerated) {
  1944. return;
  1945. }
  1946. std::string cmd = cmSystemTools::GetCMakeCommand();
  1947. cmd = cmStrCat(
  1948. this->LocalGenerator->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL),
  1949. " -E __create_def ",
  1950. this->LocalGenerator->ConvertToOutputFormat(
  1951. this->LocalGenerator->MaybeRelativeToCurBinDir(mdi->DefFile),
  1952. cmOutputConverter::SHELL),
  1953. ' ');
  1954. std::string objlist_file = mdi->DefFile + ".objs";
  1955. cmd += this->LocalGenerator->ConvertToOutputFormat(
  1956. this->LocalGenerator->MaybeRelativeToCurBinDir(objlist_file),
  1957. cmOutputConverter::SHELL);
  1958. cmProp nm_executable = this->Makefile->GetDefinition("CMAKE_NM");
  1959. if (cmNonempty(nm_executable)) {
  1960. cmd += " --nm=";
  1961. cmd += this->LocalCommonGenerator->ConvertToOutputFormat(
  1962. *nm_executable, cmOutputConverter::SHELL);
  1963. }
  1964. real_link_commands.insert(real_link_commands.begin(), cmd);
  1965. // create a list of obj files for the -E __create_def to read
  1966. cmGeneratedFileStream fout(objlist_file);
  1967. if (mdi->WindowsExportAllSymbols) {
  1968. for (std::string const& obj : this->Objects) {
  1969. if (cmHasLiteralSuffix(obj, ".obj")) {
  1970. fout << obj << "\n";
  1971. }
  1972. }
  1973. for (std::string const& obj : this->ExternalObjects) {
  1974. fout << obj << "\n";
  1975. }
  1976. }
  1977. for (cmSourceFile const* src : mdi->Sources) {
  1978. fout << src->GetFullPath() << "\n";
  1979. }
  1980. }