cmMakefileTargetGenerator.cxx 93 KB

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