cmMakefileTargetGenerator.cxx 89 KB

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