cmMakefileTargetGenerator.cxx 91 KB

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