cmMakefileTargetGenerator.cxx 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396
  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 "cmGeneratedFileStream.h"
  23. #include "cmGeneratorExpression.h"
  24. #include "cmGeneratorOptions.h"
  25. #include "cmGeneratorTarget.h"
  26. #include "cmGlobalUnixMakefileGenerator3.h"
  27. #include "cmLinkLineComputer.h" // IWYU pragma: keep
  28. #include "cmList.h"
  29. #include "cmLocalCommonGenerator.h"
  30. #include "cmLocalGenerator.h"
  31. #include "cmLocalUnixMakefileGenerator3.h"
  32. #include "cmMakefile.h"
  33. #include "cmMakefileExecutableTargetGenerator.h"
  34. #include "cmMakefileLibraryTargetGenerator.h"
  35. #include "cmMakefileUtilityTargetGenerator.h"
  36. #include "cmMessageType.h"
  37. #include "cmOutputConverter.h"
  38. #include "cmPolicies.h"
  39. #include "cmRange.h"
  40. #include "cmRulePlaceholderExpander.h"
  41. #include "cmSourceFile.h"
  42. #include "cmSourceFileLocationKind.h"
  43. #include "cmState.h"
  44. #include "cmStateDirectory.h"
  45. #include "cmStateSnapshot.h"
  46. #include "cmStateTypes.h"
  47. #include "cmStringAlgorithms.h"
  48. #include "cmSystemTools.h"
  49. #include "cmTarget.h"
  50. #include "cmValue.h"
  51. #include "cmake.h"
  52. cmMakefileTargetGenerator::cmMakefileTargetGenerator(cmGeneratorTarget* target)
  53. : cmCommonTargetGenerator(target)
  54. {
  55. this->CustomCommandDriver = OnBuild;
  56. this->LocalGenerator =
  57. static_cast<cmLocalUnixMakefileGenerator3*>(target->GetLocalGenerator());
  58. this->GlobalGenerator = static_cast<cmGlobalUnixMakefileGenerator3*>(
  59. this->LocalGenerator->GetGlobalGenerator());
  60. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  61. this->NoRuleMessages = false;
  62. if (cmValue ruleStatus =
  63. cm->GetState()->GetGlobalProperty("RULE_MESSAGES")) {
  64. this->NoRuleMessages = ruleStatus.IsOff();
  65. }
  66. switch (this->GeneratorTarget->GetPolicyStatusCMP0113()) {
  67. case cmPolicies::WARN:
  68. CM_FALLTHROUGH;
  69. case cmPolicies::OLD:
  70. this->CMP0113New = false;
  71. break;
  72. case cmPolicies::NEW:
  73. this->CMP0113New = true;
  74. break;
  75. }
  76. this->MacOSXContentGenerator =
  77. cm::make_unique<MacOSXContentGeneratorType>(this);
  78. }
  79. cmMakefileTargetGenerator::~cmMakefileTargetGenerator() = default;
  80. std::unique_ptr<cmMakefileTargetGenerator> cmMakefileTargetGenerator::New(
  81. cmGeneratorTarget* tgt)
  82. {
  83. std::unique_ptr<cmMakefileTargetGenerator> result;
  84. switch (tgt->GetType()) {
  85. case cmStateEnums::EXECUTABLE:
  86. result = cm::make_unique<cmMakefileExecutableTargetGenerator>(tgt);
  87. break;
  88. case cmStateEnums::STATIC_LIBRARY:
  89. case cmStateEnums::SHARED_LIBRARY:
  90. case cmStateEnums::MODULE_LIBRARY:
  91. case cmStateEnums::OBJECT_LIBRARY:
  92. result = cm::make_unique<cmMakefileLibraryTargetGenerator>(tgt);
  93. break;
  94. case cmStateEnums::INTERFACE_LIBRARY:
  95. case cmStateEnums::UTILITY:
  96. result = cm::make_unique<cmMakefileUtilityTargetGenerator>(tgt);
  97. break;
  98. default:
  99. return result;
  100. // break; /* unreachable */
  101. }
  102. return result;
  103. }
  104. std::string const& cmMakefileTargetGenerator::GetConfigName() const
  105. {
  106. auto const& configNames = this->LocalGenerator->GetConfigNames();
  107. assert(configNames.size() == 1);
  108. return configNames.front();
  109. }
  110. void cmMakefileTargetGenerator::GetDeviceLinkFlags(
  111. std::string& linkFlags, std::string const& linkLanguage)
  112. {
  113. cmGeneratorTarget::DeviceLinkSetter setter(*this->GetGeneratorTarget());
  114. std::vector<std::string> linkOpts;
  115. this->GeneratorTarget->GetLinkOptions(linkOpts, this->GetConfigName(),
  116. linkLanguage);
  117. this->LocalGenerator->SetLinkScriptShell(
  118. this->GlobalGenerator->GetUseLinkScript());
  119. // LINK_OPTIONS are escaped.
  120. this->LocalGenerator->AppendCompileOptions(linkFlags, linkOpts);
  121. this->LocalGenerator->SetLinkScriptShell(false);
  122. }
  123. void cmMakefileTargetGenerator::GetTargetLinkFlags(
  124. std::string& flags, std::string const& linkLanguage)
  125. {
  126. this->LocalGenerator->AppendFlags(
  127. flags, this->GeneratorTarget->GetSafeProperty("LINK_FLAGS"));
  128. std::string const linkFlagsConfig =
  129. cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(this->GetConfigName()));
  130. this->LocalGenerator->AppendFlags(
  131. flags, this->GeneratorTarget->GetSafeProperty(linkFlagsConfig));
  132. std::vector<std::string> opts;
  133. this->GeneratorTarget->GetLinkOptions(opts, this->GetConfigName(),
  134. linkLanguage);
  135. this->LocalGenerator->SetLinkScriptShell(
  136. this->GlobalGenerator->GetUseLinkScript());
  137. // LINK_OPTIONS are escaped.
  138. this->LocalGenerator->AppendCompileOptions(flags, opts);
  139. this->LocalGenerator->SetLinkScriptShell(false);
  140. this->LocalGenerator->AppendLinkerTypeFlags(
  141. flags, this->GeneratorTarget, this->GetConfigName(), linkLanguage);
  142. this->LocalGenerator->AppendPositionIndependentLinkerFlags(
  143. flags, this->GeneratorTarget, this->GetConfigName(), linkLanguage);
  144. this->LocalGenerator->AppendWarningAsErrorLinkerFlags(
  145. flags, this->GeneratorTarget, linkLanguage);
  146. this->LocalGenerator->AppendDependencyInfoLinkerFlags(
  147. flags, this->GeneratorTarget, this->GetConfigName(), linkLanguage);
  148. }
  149. void cmMakefileTargetGenerator::CreateRuleFile()
  150. {
  151. // Create a directory for this target.
  152. this->TargetBuildDirectoryFull =
  153. this->GeneratorTarget->GetSupportDirectory();
  154. this->TargetBuildDirectory = this->LocalGenerator->MaybeRelativeToCurBinDir(
  155. this->TargetBuildDirectoryFull);
  156. cmSystemTools::MakeDirectory(this->TargetBuildDirectoryFull);
  157. // Construct the rule file name.
  158. this->BuildFileName = cmStrCat(this->TargetBuildDirectory, "/build.make");
  159. this->BuildFileNameFull =
  160. cmStrCat(this->TargetBuildDirectoryFull, "/build.make");
  161. // Construct the rule file name.
  162. this->ProgressFileNameFull =
  163. cmStrCat(this->TargetBuildDirectoryFull, "/progress.make");
  164. // reset the progress count
  165. this->NumberOfProgressActions = 0;
  166. // Open the rule file. This should be copy-if-different because the
  167. // rules may depend on this file itself.
  168. this->BuildFileStream = cm::make_unique<cmGeneratedFileStream>(
  169. this->BuildFileNameFull, false,
  170. this->GlobalGenerator->GetMakefileEncoding());
  171. if (!this->BuildFileStream) {
  172. return;
  173. }
  174. this->BuildFileStream->SetCopyIfDifferent(true);
  175. this->LocalGenerator->WriteDisclaimer(*this->BuildFileStream);
  176. if (this->GlobalGenerator->AllowDeleteOnError()) {
  177. std::vector<std::string> no_depends;
  178. std::vector<std::string> no_commands;
  179. this->LocalGenerator->WriteMakeRule(
  180. *this->BuildFileStream, "Delete rule output on recipe failure.",
  181. ".DELETE_ON_ERROR", no_depends, no_commands, false);
  182. }
  183. this->LocalGenerator->WriteSpecialTargetsTop(*this->BuildFileStream);
  184. }
  185. void cmMakefileTargetGenerator::WriteTargetBuildRules()
  186. {
  187. this->GeneratorTarget->CheckCxxModuleStatus(this->GetConfigName());
  188. // -- Write the custom commands for this target
  189. // Evaluates generator expressions and expands prop_value
  190. auto evaluatedFiles = [this](std::string const& prop_value) -> cmList {
  191. cmList files{ cmGeneratorExpression::Evaluate(
  192. prop_value, this->LocalGenerator, this->GetConfigName(),
  193. this->GeneratorTarget) };
  194. return files;
  195. };
  196. // Look for additional files registered for cleaning in this directory.
  197. if (cmValue prop_value =
  198. this->Makefile->GetProperty("ADDITIONAL_MAKE_CLEAN_FILES")) {
  199. auto const files = evaluatedFiles(*prop_value);
  200. this->CleanFiles.insert(files.begin(), files.end());
  201. }
  202. // Look for additional files registered for cleaning in this target.
  203. if (cmValue prop_value =
  204. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  205. auto const files = evaluatedFiles(*prop_value);
  206. // For relative path support
  207. std::string const& binaryDir =
  208. this->LocalGenerator->GetCurrentBinaryDirectory();
  209. for (std::string const& cfl : files) {
  210. this->CleanFiles.insert(cmSystemTools::CollapseFullPath(cfl, binaryDir));
  211. }
  212. }
  213. // Look for ISPC extra object files generated by this target
  214. auto const ispcAdditionalObjs =
  215. this->GeneratorTarget->GetGeneratedISPCObjects(this->GetConfigName());
  216. for (std::string const& ispcObj : ispcAdditionalObjs) {
  217. this->CleanFiles.insert(
  218. this->LocalGenerator->MaybeRelativeToCurBinDir(ispcObj));
  219. }
  220. // add custom commands to the clean rules?
  221. bool const clean = this->Makefile->GetProperty("CLEAN_NO_CUSTOM").IsOff();
  222. // First generate the object rule files. Save a list of all object
  223. // files for this target.
  224. std::vector<cmSourceFile const*> customCommands;
  225. this->GeneratorTarget->GetCustomCommands(customCommands,
  226. this->GetConfigName());
  227. std::vector<std::string> codegen_depends;
  228. codegen_depends.reserve(customCommands.size());
  229. for (cmSourceFile const* sf : customCommands) {
  230. if (this->CMP0113New &&
  231. !this->LocalGenerator->GetCommandsVisited(this->GeneratorTarget)
  232. .insert(sf)
  233. .second) {
  234. continue;
  235. }
  236. cmCustomCommandGenerator ccg(*sf->GetCustomCommand(),
  237. this->GetConfigName(), this->LocalGenerator);
  238. this->GenerateCustomRuleFile(ccg);
  239. if (clean) {
  240. std::vector<std::string> const& outputs = ccg.GetOutputs();
  241. for (std::string const& output : outputs) {
  242. this->CleanFiles.insert(
  243. this->LocalGenerator->MaybeRelativeToCurBinDir(output));
  244. }
  245. std::vector<std::string> const& byproducts = ccg.GetByproducts();
  246. for (std::string const& byproduct : byproducts) {
  247. this->CleanFiles.insert(
  248. this->LocalGenerator->MaybeRelativeToCurBinDir(byproduct));
  249. }
  250. }
  251. if (ccg.GetCC().GetCodegen()) {
  252. std::string const& output = ccg.GetOutputs().front();
  253. // We always attach the actual commands to the first output.
  254. codegen_depends.emplace_back(output);
  255. }
  256. }
  257. // Some make tools need a special dependency for an empty rule.
  258. if (codegen_depends.empty()) {
  259. std::string hack = this->GlobalGenerator->GetEmptyRuleHackDepends();
  260. if (!hack.empty()) {
  261. codegen_depends.emplace_back(std::move(hack));
  262. }
  263. }
  264. // Construct the codegen target.
  265. {
  266. std::string const codegenTarget = cmStrCat(
  267. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget),
  268. "/codegen");
  269. // Write the rule.
  270. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  271. codegenTarget, codegen_depends, {},
  272. true);
  273. }
  274. // Add byproducts from build events to the clean rules
  275. if (clean) {
  276. std::vector<cmCustomCommand> buildEventCommands =
  277. this->GeneratorTarget->GetPreBuildCommands();
  278. cm::append(buildEventCommands,
  279. this->GeneratorTarget->GetPreLinkCommands());
  280. cm::append(buildEventCommands,
  281. this->GeneratorTarget->GetPostBuildCommands());
  282. for (auto const& be : buildEventCommands) {
  283. cmCustomCommandGenerator beg(be, this->GetConfigName(),
  284. this->LocalGenerator);
  285. std::vector<std::string> const& byproducts = beg.GetByproducts();
  286. for (std::string const& byproduct : byproducts) {
  287. this->CleanFiles.insert(
  288. this->LocalGenerator->MaybeRelativeToCurBinDir(byproduct));
  289. }
  290. }
  291. }
  292. std::vector<cmSourceFile const*> headerSources;
  293. this->GeneratorTarget->GetHeaderSources(headerSources,
  294. this->GetConfigName());
  295. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  296. headerSources, this->MacOSXContentGenerator.get(), this->GetConfigName());
  297. std::vector<cmSourceFile const*> extraSources;
  298. this->GeneratorTarget->GetExtraSources(extraSources, this->GetConfigName());
  299. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  300. extraSources, this->MacOSXContentGenerator.get(), this->GetConfigName());
  301. cmValue pchExtension = this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  302. std::vector<cmSourceFile const*> externalObjects;
  303. this->GeneratorTarget->GetExternalObjects(externalObjects,
  304. this->GetConfigName());
  305. for (cmSourceFile const* sf : externalObjects) {
  306. auto const& objectFileName = sf->GetFullPath();
  307. if (!cmHasSuffix(objectFileName, pchExtension)) {
  308. this->ExternalObjects.push_back(objectFileName);
  309. }
  310. }
  311. std::map<std::string, std::string> file_set_map;
  312. auto const* tgt = this->GeneratorTarget->Target;
  313. for (auto const& name : tgt->GetAllFileSetNames()) {
  314. auto const* file_set = tgt->GetFileSet(name);
  315. if (!file_set) {
  316. this->Makefile->IssueMessage(
  317. MessageType::INTERNAL_ERROR,
  318. cmStrCat("Target \"", tgt->GetName(),
  319. "\" is tracked to have file set \"", name,
  320. "\", but it was not found."));
  321. continue;
  322. }
  323. auto fileEntries = file_set->CompileFileEntries();
  324. auto directoryEntries = file_set->CompileDirectoryEntries();
  325. auto directories = file_set->EvaluateDirectoryEntries(
  326. directoryEntries, this->LocalGenerator, this->GetConfigName(),
  327. this->GeneratorTarget);
  328. std::map<std::string, std::vector<std::string>> files;
  329. for (auto const& entry : fileEntries) {
  330. file_set->EvaluateFileEntry(directories, files, entry,
  331. this->LocalGenerator, this->GetConfigName(),
  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.CMTargetLabels = this->GeneratorTarget->GetTargetLabelsString().c_str();
  830. vars.Language = lang.c_str();
  831. vars.Target = targetOutPathReal.c_str();
  832. vars.TargetPDB = targetOutPathPDB.c_str();
  833. vars.TargetCompilePDB = targetOutPathCompilePDB.c_str();
  834. vars.Source = sourceFile.c_str();
  835. std::string const shellObj =
  836. this->LocalGenerator->ConvertToOutputFormat(obj, cmOutputConverter::SHELL);
  837. vars.Object = shellObj.c_str();
  838. std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
  839. objectDir = this->LocalGenerator->ConvertToOutputFormat(
  840. this->LocalGenerator->MaybeRelativeToCurBinDir(objectDir),
  841. cmOutputConverter::SHELL);
  842. vars.ObjectDir = objectDir.c_str();
  843. std::string objectFileDir = cmSystemTools::GetFilenamePath(obj);
  844. objectFileDir = this->LocalGenerator->ConvertToOutputFormat(
  845. this->LocalGenerator->MaybeRelativeToCurBinDir(objectFileDir),
  846. cmOutputConverter::SHELL);
  847. vars.ObjectFileDir = objectFileDir.c_str();
  848. vars.Flags = flags.c_str();
  849. vars.ISPCHeader = ispcHeaderForShell.c_str();
  850. vars.Config = this->GetConfigName().c_str();
  851. std::string definesString = cmStrCat("$(", lang, "_DEFINES)");
  852. this->LocalGenerator->JoinDefines(defines, definesString, lang);
  853. vars.Defines = definesString.c_str();
  854. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  855. includes, this->GeneratorTarget, lang, config);
  856. this->LocalGenerator->AppendFlags(includesString,
  857. "$(" + lang + "_INCLUDES)");
  858. vars.Includes = includesString.c_str();
  859. std::string dependencyTarget;
  860. std::string shellDependencyFile;
  861. std::string dependencyTimestamp;
  862. if (compilerGenerateDeps) {
  863. dependencyTarget = this->LocalGenerator->EscapeForShell(
  864. this->LocalGenerator->ConvertToMakefilePath(
  865. this->LocalGenerator->MaybeRelativeToTopBinDir(relativeObj)));
  866. vars.DependencyTarget = dependencyTarget.c_str();
  867. auto depFile = cmStrCat(obj, ".d");
  868. shellDependencyFile = this->LocalGenerator->ConvertToOutputFormat(
  869. depFile, cmOutputConverter::SHELL);
  870. vars.DependencyFile = shellDependencyFile.c_str();
  871. this->CleanFiles.insert(depFile);
  872. dependencyTimestamp = this->LocalGenerator->MaybeRelativeToTopBinDir(
  873. cmStrCat(this->TargetBuildDirectoryFull, "/compiler_depend.ts"));
  874. }
  875. // At the moment, it is assumed that C, C++, Fortran, and CUDA have both
  876. // assembly and preprocessor capabilities. The same is true for the
  877. // ability to export compile commands
  878. bool const lang_has_preprocessor =
  879. ((lang == "C") || (lang == "CXX") || (lang == "OBJC") ||
  880. (lang == "OBJCXX") || (lang == "Fortran") || (lang == "CUDA") ||
  881. lang == "ISPC" || lang == "HIP" || lang == "ASM");
  882. bool const lang_has_assembly = lang_has_preprocessor;
  883. bool const lang_can_export_cmds = lang_has_preprocessor;
  884. auto rulePlaceholderExpander =
  885. this->LocalGenerator->CreateRulePlaceholderExpander();
  886. // Construct the compile rules.
  887. {
  888. std::string cudaCompileMode;
  889. if (lang == "CUDA") {
  890. if (this->GeneratorTarget->GetPropertyAsBool(
  891. "CUDA_SEPARABLE_COMPILATION")) {
  892. std::string const& rdcFlag =
  893. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_RDC_FLAG");
  894. cudaCompileMode = cmStrCat(cudaCompileMode, rdcFlag, ' ');
  895. }
  896. static std::array<cm::string_view, 4> const compileModes{
  897. { "PTX"_s, "CUBIN"_s, "FATBIN"_s, "OPTIX"_s }
  898. };
  899. bool useNormalCompileMode = true;
  900. for (cm::string_view mode : compileModes) {
  901. auto propName = cmStrCat("CUDA_", mode, "_COMPILATION");
  902. auto defName = cmStrCat("_CMAKE_CUDA_", mode, "_FLAG");
  903. if (this->GeneratorTarget->GetPropertyAsBool(propName)) {
  904. std::string const& flag =
  905. this->Makefile->GetRequiredDefinition(defName);
  906. cudaCompileMode = cmStrCat(cudaCompileMode, flag);
  907. useNormalCompileMode = false;
  908. break;
  909. }
  910. }
  911. if (useNormalCompileMode) {
  912. std::string const& wholeFlag =
  913. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_WHOLE_FLAG");
  914. cudaCompileMode = cmStrCat(cudaCompileMode, wholeFlag);
  915. }
  916. vars.CudaCompileMode = cudaCompileMode.c_str();
  917. }
  918. cmList compileCommands;
  919. std::string const& compileRule = this->Makefile->GetRequiredDefinition(
  920. "CMAKE_" + lang + "_COMPILE_OBJECT");
  921. compileCommands.assign(compileRule);
  922. if (this->GeneratorTarget->GetPropertyAsBool("EXPORT_COMPILE_COMMANDS") &&
  923. lang_can_export_cmds && compileCommands.size() == 1) {
  924. std::string compileCommand = compileCommands[0];
  925. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  926. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  927. compileCommand, vars);
  928. std::string const workingDirectory =
  929. this->LocalGenerator->GetCurrentBinaryDirectory();
  930. std::string::size_type lfPos = compileCommand.find(langFlags);
  931. if (lfPos != std::string::npos) {
  932. compileCommand.replace(lfPos, langFlags.size(),
  933. this->GetFlags(lang, this->GetConfigName()));
  934. }
  935. std::string const langDefines = std::string("$(") + lang + "_DEFINES)";
  936. std::string::size_type const ldPos = compileCommand.find(langDefines);
  937. if (ldPos != std::string::npos) {
  938. compileCommand.replace(ldPos, langDefines.size(),
  939. this->GetDefines(lang, this->GetConfigName()));
  940. }
  941. std::string const langIncludes = std::string("$(") + lang + "_INCLUDES)";
  942. std::string::size_type const liPos = compileCommand.find(langIncludes);
  943. if (liPos != std::string::npos) {
  944. compileCommand.replace(liPos, langIncludes.size(),
  945. this->GetIncludes(lang, this->GetConfigName()));
  946. }
  947. cmValue const eliminate[] = {
  948. this->Makefile->GetDefinition("CMAKE_START_TEMP_FILE"),
  949. this->Makefile->GetDefinition("CMAKE_END_TEMP_FILE")
  950. };
  951. for (cmValue const& el : eliminate) {
  952. if (el) {
  953. cmSystemTools::ReplaceString(compileCommand, *el, "");
  954. }
  955. }
  956. this->GlobalGenerator->AddCXXCompileCommand(
  957. source.GetFullPath(), workingDirectory, compileCommand, relativeObj);
  958. }
  959. // See if we need to use a compiler launcher like ccache or distcc
  960. std::string compilerLauncher;
  961. if (!compileCommands.empty()) {
  962. compilerLauncher = GetCompilerLauncher(lang, config);
  963. }
  964. cmValue const skipCodeCheck = source.GetProperty("SKIP_LINTING");
  965. if (!skipCodeCheck.IsOn()) {
  966. std::string const codeCheck = this->GenerateCodeCheckRules(
  967. source, compilerLauncher, "$(CMAKE_COMMAND)", config, nullptr);
  968. if (!codeCheck.empty()) {
  969. compileCommands.front().insert(0, codeCheck);
  970. }
  971. }
  972. // If compiler launcher was specified and not consumed above, it
  973. // goes to the beginning of the command line.
  974. if (!compileCommands.empty() && !compilerLauncher.empty()) {
  975. cmList args{ compilerLauncher, cmList::EmptyElements::Yes };
  976. if (!args.empty()) {
  977. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  978. args[0], cmOutputConverter::SHELL);
  979. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  980. i = this->LocalGenerator->EscapeForShell(i);
  981. }
  982. }
  983. compileCommands.front().insert(0, args.join(" ") + " ");
  984. }
  985. std::string launcher;
  986. {
  987. std::string val = this->LocalGenerator->GetRuleLauncher(
  988. this->GeneratorTarget, "RULE_LAUNCH_COMPILE",
  989. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  990. if (cmNonempty(val)) {
  991. launcher = cmStrCat(val, ' ');
  992. }
  993. }
  994. std::string flagsWithDeps(flags);
  995. if (compilerGenerateDeps) {
  996. // Injects dependency computation
  997. auto depFlags = this->Makefile->GetSafeDefinition(
  998. cmStrCat("CMAKE_DEPFILE_FLAGS_", lang));
  999. if (!depFlags.empty()) {
  1000. // Add dependency flags
  1001. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  1002. depFlags, vars);
  1003. flagsWithDeps.append(1, ' ');
  1004. flagsWithDeps.append(depFlags);
  1005. }
  1006. vars.Flags = flagsWithDeps.c_str();
  1007. auto const& extraCommands = this->Makefile->GetSafeDefinition(
  1008. cmStrCat("CMAKE_", lang, "_DEPENDS_EXTRA_COMMANDS"));
  1009. if (!extraCommands.empty()) {
  1010. compileCommands.append(extraCommands);
  1011. }
  1012. auto const& depFormat = this->Makefile->GetRequiredDefinition(
  1013. cmStrCat("CMAKE_", lang, "_DEPFILE_FORMAT"));
  1014. if (depFormat == "msvc"_s) {
  1015. // compiler must be launched through a wrapper to pick-up dependencies
  1016. std::string depFilter =
  1017. "$(CMAKE_COMMAND) -E cmake_cl_compile_depends ";
  1018. depFilter += cmStrCat("--dep-file=", shellDependencyFile);
  1019. depFilter +=
  1020. cmStrCat(" --working-dir=",
  1021. this->LocalGenerator->ConvertToOutputFormat(
  1022. this->LocalGenerator->GetCurrentBinaryDirectory(),
  1023. cmOutputConverter::SHELL));
  1024. auto const& prefix = this->Makefile->GetSafeDefinition(
  1025. cmStrCat("CMAKE_", lang, "_CL_SHOWINCLUDES_PREFIX"));
  1026. depFilter += cmStrCat(" --filter-prefix=",
  1027. this->LocalGenerator->ConvertToOutputFormat(
  1028. prefix, cmOutputConverter::SHELL));
  1029. depFilter += " -- ";
  1030. compileCommands.front().insert(0, depFilter);
  1031. }
  1032. }
  1033. // Expand placeholders in the commands.
  1034. for (std::string& compileCommand : compileCommands) {
  1035. compileCommand = cmStrCat(launcher, compileCommand);
  1036. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  1037. compileCommand, vars);
  1038. }
  1039. // Change the command working directory to the local build tree.
  1040. this->LocalGenerator->CreateCDCommand(
  1041. compileCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  1042. this->LocalGenerator->GetBinaryDirectory());
  1043. cm::append(commands, compileCommands);
  1044. }
  1045. // Check for extra outputs created by the compilation.
  1046. cmList outputs;
  1047. outputs.emplace_back(relativeObj);
  1048. if (cmValue extra_outputs_str = source.GetProperty("OBJECT_OUTPUTS")) {
  1049. std::string evaluated_outputs = cmGeneratorExpression::Evaluate(
  1050. *extra_outputs_str, this->LocalGenerator, config);
  1051. if (!evaluated_outputs.empty()) {
  1052. // Register these as extra files to clean.
  1053. outputs.append(evaluated_outputs);
  1054. }
  1055. }
  1056. if (!ispcHeaderRelative.empty()) {
  1057. // can't move ispcHeader as vars is using it
  1058. outputs.emplace_back(ispcHeaderRelative);
  1059. }
  1060. if (outputs.size() > 1) {
  1061. this->CleanFiles.insert(outputs.begin() + 1, outputs.end());
  1062. }
  1063. if (compilerGenerateDeps) {
  1064. depends.push_back(dependencyTimestamp);
  1065. }
  1066. // Write the rule.
  1067. this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
  1068. commands);
  1069. if (compilerGenerateDeps) {
  1070. // set back flags without dependency generation
  1071. vars.Flags = flags.c_str();
  1072. }
  1073. bool do_preprocess_rules = lang_has_preprocessor &&
  1074. this->LocalGenerator->GetCreatePreprocessedSourceRules();
  1075. bool do_assembly_rules =
  1076. lang_has_assembly && this->LocalGenerator->GetCreateAssemblySourceRules();
  1077. if (do_preprocess_rules || do_assembly_rules) {
  1078. std::vector<std::string> force_depends;
  1079. force_depends.emplace_back("cmake_force");
  1080. std::string::size_type dot_pos = relativeObj.rfind('.');
  1081. std::string relativeObjBase = relativeObj.substr(0, dot_pos);
  1082. dot_pos = obj.rfind('.');
  1083. std::string objBase = obj.substr(0, dot_pos);
  1084. if (do_preprocess_rules) {
  1085. commands.clear();
  1086. std::string const relativeObjI = relativeObjBase + ".i";
  1087. std::string const objI = objBase + ".i";
  1088. std::string preprocessEcho =
  1089. cmStrCat("Preprocessing ", lang, " source to ", objI);
  1090. this->LocalGenerator->AppendEcho(
  1091. commands, preprocessEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  1092. std::string preprocessRuleVar =
  1093. cmStrCat("CMAKE_", lang, "_CREATE_PREPROCESSED_SOURCE");
  1094. if (cmValue preprocessRule =
  1095. this->Makefile->GetDefinition(preprocessRuleVar)) {
  1096. cmList preprocessCommands{ *preprocessRule };
  1097. std::string shellObjI = this->LocalGenerator->ConvertToOutputFormat(
  1098. objI, cmOutputConverter::SHELL);
  1099. vars.PreprocessedSource = shellObjI.c_str();
  1100. // Expand placeholders in the commands.
  1101. for (std::string& preprocessCommand : preprocessCommands) {
  1102. // no launcher for preprocessor commands
  1103. rulePlaceholderExpander->ExpandRuleVariables(
  1104. this->LocalGenerator, preprocessCommand, vars);
  1105. }
  1106. this->LocalGenerator->CreateCDCommand(
  1107. preprocessCommands,
  1108. this->LocalGenerator->GetCurrentBinaryDirectory(),
  1109. this->LocalGenerator->GetBinaryDirectory());
  1110. cm::append(commands, preprocessCommands);
  1111. } else {
  1112. std::string cmd =
  1113. cmStrCat("$(CMAKE_COMMAND) -E cmake_unimplemented_variable ",
  1114. preprocessRuleVar);
  1115. commands.push_back(std::move(cmd));
  1116. }
  1117. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1118. relativeObjI, force_depends,
  1119. commands, false);
  1120. }
  1121. if (do_assembly_rules) {
  1122. commands.clear();
  1123. std::string relativeObjS = relativeObjBase + ".s";
  1124. std::string objS = objBase + ".s";
  1125. std::string assemblyEcho =
  1126. cmStrCat("Compiling ", lang, " source to assembly ", objS);
  1127. this->LocalGenerator->AppendEcho(
  1128. commands, assemblyEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  1129. std::string assemblyRuleVar =
  1130. cmStrCat("CMAKE_", lang, "_CREATE_ASSEMBLY_SOURCE");
  1131. if (cmValue assemblyRule =
  1132. this->Makefile->GetDefinition(assemblyRuleVar)) {
  1133. cmList assemblyCommands{ *assemblyRule };
  1134. std::string shellObjS = this->LocalGenerator->ConvertToOutputFormat(
  1135. objS, cmOutputConverter::SHELL);
  1136. vars.AssemblySource = shellObjS.c_str();
  1137. // Expand placeholders in the commands.
  1138. for (std::string& assemblyCommand : assemblyCommands) {
  1139. // no launcher for assembly commands
  1140. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  1141. assemblyCommand, vars);
  1142. }
  1143. this->LocalGenerator->CreateCDCommand(
  1144. assemblyCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  1145. this->LocalGenerator->GetBinaryDirectory());
  1146. cm::append(commands, assemblyCommands);
  1147. } else {
  1148. std::string cmd =
  1149. cmStrCat("$(CMAKE_COMMAND) -E cmake_unimplemented_variable ",
  1150. assemblyRuleVar);
  1151. commands.push_back(std::move(cmd));
  1152. }
  1153. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1154. relativeObjS, force_depends,
  1155. commands, false);
  1156. }
  1157. }
  1158. }
  1159. void cmMakefileTargetGenerator::WriteTargetCleanRules()
  1160. {
  1161. std::vector<std::string> depends;
  1162. std::vector<std::string> commands;
  1163. // Construct the clean target name.
  1164. std::string const cleanTarget = cmStrCat(
  1165. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget),
  1166. "/clean");
  1167. // Construct the clean command.
  1168. this->LocalGenerator->AppendCleanCommand(commands, this->CleanFiles,
  1169. this->GeneratorTarget);
  1170. this->LocalGenerator->CreateCDCommand(
  1171. commands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  1172. this->LocalGenerator->GetBinaryDirectory());
  1173. // Write the rule.
  1174. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1175. cleanTarget, depends, commands, true);
  1176. }
  1177. bool cmMakefileTargetGenerator::WriteMakeRule(
  1178. std::ostream& os, char const* comment,
  1179. std::vector<std::string> const& outputs,
  1180. std::vector<std::string> const& depends,
  1181. std::vector<std::string> const& commands, bool in_help)
  1182. {
  1183. bool symbolic = false;
  1184. if (outputs.empty()) {
  1185. return symbolic;
  1186. }
  1187. // Check whether we need to bother checking for a symbolic output.
  1188. bool const need_symbolic = this->GlobalGenerator->GetNeedSymbolicMark();
  1189. // Check whether the first output is marked as symbolic.
  1190. if (need_symbolic) {
  1191. if (cmSourceFile* sf = this->Makefile->GetSource(outputs[0])) {
  1192. symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  1193. }
  1194. }
  1195. // We always attach the actual commands to the first output.
  1196. this->LocalGenerator->WriteMakeRule(os, comment, outputs[0], depends,
  1197. commands, symbolic, in_help);
  1198. // For single outputs, we are done.
  1199. if (outputs.size() == 1) {
  1200. return symbolic;
  1201. }
  1202. // For multiple outputs, make the extra ones depend on the first one.
  1203. std::vector<std::string> const output_depends(1, outputs[0]);
  1204. for (std::string const& output : cmMakeRange(outputs).advance(1)) {
  1205. // Touch the extra output so "make" knows that it was updated,
  1206. // but only if the output was actually created.
  1207. std::string const out = this->LocalGenerator->ConvertToOutputFormat(
  1208. this->LocalGenerator->MaybeRelativeToTopBinDir(output),
  1209. cmOutputConverter::SHELL);
  1210. std::vector<std::string> output_commands;
  1211. bool o_symbolic = false;
  1212. if (need_symbolic) {
  1213. if (cmSourceFile const* sf = this->Makefile->GetSource(output)) {
  1214. o_symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  1215. }
  1216. }
  1217. symbolic = symbolic && o_symbolic;
  1218. if (!o_symbolic) {
  1219. output_commands.push_back("@$(CMAKE_COMMAND) -E touch_nocreate " + out);
  1220. }
  1221. this->LocalGenerator->WriteMakeRule(os, nullptr, output, output_depends,
  1222. output_commands, o_symbolic, in_help);
  1223. if (!o_symbolic) {
  1224. // At build time, remove the first output if this one does not exist
  1225. // so that "make" will rerun the real commands that create this one.
  1226. MultipleOutputPairsType::value_type p(output, outputs[0]);
  1227. this->MultipleOutputPairs.insert(p);
  1228. }
  1229. }
  1230. return symbolic;
  1231. }
  1232. void cmMakefileTargetGenerator::WriteTargetLinkDependRules()
  1233. {
  1234. if (!this->GeneratorTarget->HasLinkDependencyFile(this->GetConfigName())) {
  1235. return;
  1236. }
  1237. auto depFile = this->LocalGenerator->GetLinkDependencyFile(
  1238. this->GeneratorTarget, this->GetConfigName());
  1239. this->CleanFiles.insert(depFile);
  1240. this->LocalGenerator->AddImplicitDepends(
  1241. this->GeneratorTarget, "LINK",
  1242. this->GeneratorTarget->GetFullPath(this->GetConfigName()), depFile,
  1243. cmDependencyScannerKind::Compiler);
  1244. }
  1245. std::string cmMakefileTargetGenerator::GetClangTidyReplacementsFilePath(
  1246. std::string const& directory, cmSourceFile const& source,
  1247. std::string const& config) const
  1248. {
  1249. (void)config;
  1250. auto const& objectName = this->GeneratorTarget->GetObjectName(&source);
  1251. // NOTE: This may be better to use `this->TargetBuildDirectory` instead of
  1252. // `MaybeRelativeToTopBinDir(this->TargetBuildDirectoryFull)` here. The main
  1253. // difference is that the current behavior looks odd to relative
  1254. // `<LANG>_CLANG_TIDY_EXPORT_FIXES_DIR` settings. Each subdirectory has its
  1255. // own export fixes directory *and* adds its relative-from-root path
  1256. // underneath it. However, when using an absolute export fixes directory, the
  1257. // source directory structure is preserved. The main benefit of the former is
  1258. // shorter paths everywhere versus the status quo of the existing code.
  1259. cmLocalGenerator* lg = this->GeneratorTarget->GetLocalGenerator();
  1260. auto fixesFile = cmSystemTools::CollapseFullPath(
  1261. cmStrCat(directory, '/',
  1262. lg->CreateSafeObjectFileName(
  1263. lg->MaybeRelativeToTopBinDir(this->TargetBuildDirectoryFull)),
  1264. '/', objectName, ".yaml"));
  1265. return fixesFile;
  1266. }
  1267. void cmMakefileTargetGenerator::WriteTargetDependRules()
  1268. {
  1269. // must write the targets depend info file
  1270. this->InfoFileNameFull =
  1271. cmStrCat(this->TargetBuildDirectoryFull, "/DependInfo.cmake");
  1272. this->InfoFileStream =
  1273. cm::make_unique<cmGeneratedFileStream>(this->InfoFileNameFull);
  1274. if (!this->InfoFileStream) {
  1275. return;
  1276. }
  1277. this->InfoFileStream->SetCopyIfDifferent(true);
  1278. this->LocalGenerator->WriteDependLanguageInfo(*this->InfoFileStream,
  1279. this->GeneratorTarget);
  1280. // Store multiple output pairs in the depend info file.
  1281. if (!this->MultipleOutputPairs.empty()) {
  1282. /* clang-format off */
  1283. *this->InfoFileStream
  1284. << "\n"
  1285. << "# Pairs of files generated by the same build rule.\n"
  1286. << "set(CMAKE_MULTIPLE_OUTPUT_PAIRS\n";
  1287. /* clang-format on */
  1288. for (auto const& pi : this->MultipleOutputPairs) {
  1289. *this->InfoFileStream
  1290. << " " << cmOutputConverter::EscapeForCMake(pi.first) << " "
  1291. << cmOutputConverter::EscapeForCMake(pi.second) << "\n";
  1292. }
  1293. *this->InfoFileStream << " )\n\n";
  1294. }
  1295. // Store list of targets linked directly or transitively.
  1296. {
  1297. /* clang-format off */
  1298. *this->InfoFileStream
  1299. << "\n"
  1300. "# Targets to which this target links which contain Fortran sources.\n"
  1301. "set(CMAKE_Fortran_TARGET_LINKED_INFO_FILES\n";
  1302. /* clang-format on */
  1303. auto const dirs =
  1304. this->GetLinkedTargetDirectories("Fortran", this->GetConfigName());
  1305. for (std::string const& d : dirs.Direct) {
  1306. *this->InfoFileStream << " \"" << d << "/DependInfo.cmake\"\n";
  1307. }
  1308. *this->InfoFileStream << " )\n";
  1309. /* clang-format off */
  1310. *this->InfoFileStream
  1311. << "\n"
  1312. "# Targets to which this target links which contain Fortran sources.\n"
  1313. "set(CMAKE_Fortran_TARGET_FORWARD_LINKED_INFO_FILES\n";
  1314. /* clang-format on */
  1315. for (std::string const& d : dirs.Forward) {
  1316. *this->InfoFileStream << " \"" << d << "/DependInfo.cmake\"\n";
  1317. }
  1318. *this->InfoFileStream << " )\n";
  1319. }
  1320. std::string const& working_dir =
  1321. this->LocalGenerator->GetCurrentBinaryDirectory();
  1322. /* clang-format off */
  1323. *this->InfoFileStream
  1324. << "\n"
  1325. << "# Fortran module output directory.\n"
  1326. << "set(CMAKE_Fortran_TARGET_MODULE_DIR \""
  1327. << this->GeneratorTarget->GetFortranModuleDirectory(working_dir)
  1328. << "\")\n";
  1329. if (this->GeneratorTarget->IsFortranBuildingIntrinsicModules()) {
  1330. *this->InfoFileStream
  1331. << "\n"
  1332. << "# Fortran compiler is building intrinsic modules.\n"
  1333. << "set(CMAKE_Fortran_TARGET_BUILDING_INTRINSIC_MODULES ON) \n";
  1334. }
  1335. /* clang-format on */
  1336. // and now write the rule to use it
  1337. std::vector<std::string> depends;
  1338. std::vector<std::string> commands;
  1339. // Construct the name of the dependency generation target.
  1340. std::string const depTarget = cmStrCat(
  1341. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget),
  1342. "/depend");
  1343. // Add a command to call CMake to scan dependencies. CMake will
  1344. // touch the corresponding depends file after scanning dependencies.
  1345. std::ostringstream depCmd;
  1346. // TODO: Account for source file properties and directory-level
  1347. // definitions when scanning for dependencies.
  1348. #if !defined(_WIN32) || defined(__CYGWIN__)
  1349. // This platform supports symlinks, so cmSystemTools will translate
  1350. // paths. Make sure PWD is set to the original name of the home
  1351. // output directory to help cmSystemTools to create the same
  1352. // translation table for the dependency scanning process.
  1353. depCmd << "cd "
  1354. << (this->LocalGenerator->ConvertToOutputFormat(
  1355. this->LocalGenerator->GetBinaryDirectory(),
  1356. cmOutputConverter::SHELL))
  1357. << " && ";
  1358. #endif
  1359. // Generate a call this signature:
  1360. //
  1361. // cmake -E cmake_depends <generator>
  1362. // <home-src-dir> <start-src-dir>
  1363. // <home-out-dir> <start-out-dir>
  1364. // <dep-info> --color=$(COLOR)
  1365. //
  1366. // This gives the dependency scanner enough information to recreate
  1367. // the state of our local generator sufficiently for its needs.
  1368. depCmd << "$(CMAKE_COMMAND) -E cmake_depends \""
  1369. << this->GlobalGenerator->GetName() << "\" "
  1370. << this->LocalGenerator->ConvertToOutputFormat(
  1371. this->LocalGenerator->GetSourceDirectory(),
  1372. cmOutputConverter::SHELL)
  1373. << " "
  1374. << this->LocalGenerator->ConvertToOutputFormat(
  1375. this->LocalGenerator->GetCurrentSourceDirectory(),
  1376. cmOutputConverter::SHELL)
  1377. << " "
  1378. << this->LocalGenerator->ConvertToOutputFormat(
  1379. this->LocalGenerator->GetBinaryDirectory(),
  1380. cmOutputConverter::SHELL)
  1381. << " "
  1382. << this->LocalGenerator->ConvertToOutputFormat(
  1383. this->LocalGenerator->GetCurrentBinaryDirectory(),
  1384. cmOutputConverter::SHELL)
  1385. << " "
  1386. << this->LocalGenerator->ConvertToOutputFormat(
  1387. this->InfoFileNameFull, cmOutputConverter::SHELL);
  1388. if (this->LocalGenerator->GetColorMakefile()) {
  1389. depCmd << " \"--color=$(COLOR)\"";
  1390. }
  1391. commands.push_back(depCmd.str());
  1392. // Make sure all custom command outputs in this target are built.
  1393. if (this->CustomCommandDriver == OnDepends) {
  1394. this->DriveCustomCommands(depends);
  1395. }
  1396. // Write the rule.
  1397. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1398. depTarget, depends, commands, true);
  1399. }
  1400. void cmMakefileTargetGenerator::DriveCustomCommands(
  1401. std::vector<std::string>& depends)
  1402. {
  1403. // Depend on all custom command outputs.
  1404. cm::append(depends, this->CustomCommandOutputs);
  1405. }
  1406. void cmMakefileTargetGenerator::WriteObjectDependRules(
  1407. cmSourceFile const& source, std::vector<std::string>& depends)
  1408. {
  1409. // Create the list of dependencies known at cmake time. These are
  1410. // shared between the object file and dependency scanning rule.
  1411. depends.push_back(source.GetFullPath());
  1412. if (cmValue objectDeps = source.GetProperty("OBJECT_DEPENDS")) {
  1413. cmExpandList(*objectDeps, depends);
  1414. }
  1415. }
  1416. void cmMakefileTargetGenerator::WriteDeviceLinkRule(
  1417. std::vector<std::string>& commands, std::string const& output)
  1418. {
  1419. std::string architecturesStr =
  1420. this->GeneratorTarget->GetSafeProperty("CUDA_ARCHITECTURES");
  1421. if (cmIsOff(architecturesStr)) {
  1422. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  1423. "CUDA_SEPARABLE_COMPILATION on Clang "
  1424. "requires CUDA_ARCHITECTURES to be set.");
  1425. return;
  1426. }
  1427. cmLocalUnixMakefileGenerator3* localGen{ this->LocalGenerator };
  1428. cmList architectures{ architecturesStr };
  1429. std::string const& relPath = localGen->GetHomeRelativeOutputPath();
  1430. // Ensure there are no duplicates.
  1431. std::vector<std::string> const linkDeps = [&]() -> std::vector<std::string> {
  1432. std::vector<std::string> deps;
  1433. this->AppendTargetDepends(deps, true);
  1434. this->GeneratorTarget->GetLinkDepends(deps, this->GetConfigName(), "CUDA");
  1435. for (std::string const& obj : this->Objects) {
  1436. deps.emplace_back(cmStrCat(relPath, obj));
  1437. }
  1438. std::unordered_set<std::string> const depsSet(deps.begin(), deps.end());
  1439. deps.clear();
  1440. std::copy(depsSet.begin(), depsSet.end(), std::back_inserter(deps));
  1441. return deps;
  1442. }();
  1443. std::string const objectDir = this->GeneratorTarget->ObjectDirectory;
  1444. std::string const relObjectDir =
  1445. localGen->MaybeRelativeToCurBinDir(objectDir);
  1446. // Construct a list of files associated with this executable that
  1447. // may need to be cleaned.
  1448. std::vector<std::string> cleanFiles;
  1449. cleanFiles.push_back(localGen->MaybeRelativeToCurBinDir(output));
  1450. std::string profiles;
  1451. std::vector<std::string> fatbinaryDepends;
  1452. std::string const registerFile =
  1453. cmStrCat(objectDir, "cmake_cuda_register.h");
  1454. // Link device code for each architecture.
  1455. for (std::string const& architectureKind : architectures) {
  1456. std::string registerFileCmd;
  1457. // The generated register file contains macros that when expanded
  1458. // register the device routines. Because the routines are the same for
  1459. // all architectures the register file will be the same too. Thus
  1460. // generate it only on the first invocation to reduce overhead.
  1461. if (fatbinaryDepends.empty()) {
  1462. std::string const registerFileRel =
  1463. cmStrCat(relPath, relObjectDir, "cmake_cuda_register.h");
  1464. registerFileCmd =
  1465. cmStrCat(" --register-link-binaries=", registerFileRel);
  1466. cleanFiles.push_back(registerFileRel);
  1467. }
  1468. // Clang always generates real code, so strip the specifier.
  1469. std::string const architecture =
  1470. architectureKind.substr(0, architectureKind.find('-'));
  1471. std::string const cubin =
  1472. cmStrCat(objectDir, "sm_", architecture, ".cubin");
  1473. profiles += cmStrCat(" -im=profile=sm_", architecture, ",file=", cubin);
  1474. fatbinaryDepends.emplace_back(cubin);
  1475. std::string command = cmStrCat(
  1476. this->Makefile->GetRequiredDefinition("CMAKE_CUDA_DEVICE_LINKER"),
  1477. " -arch=sm_", architecture, registerFileCmd, " -o=$@ ",
  1478. cmJoin(linkDeps, " "));
  1479. localGen->WriteMakeRule(*this->BuildFileStream, nullptr, cubin, linkDeps,
  1480. { command }, false);
  1481. }
  1482. // Combine all architectures into a single fatbinary.
  1483. std::string const fatbinaryCommand =
  1484. cmStrCat(this->Makefile->GetRequiredDefinition("CMAKE_CUDA_FATBINARY"),
  1485. " -64 -cmdline=--compile-only -compress-all -link "
  1486. "--embedded-fatbin=$@",
  1487. profiles);
  1488. std::string const fatbinaryOutput =
  1489. cmStrCat(objectDir, "cmake_cuda_fatbin.h");
  1490. std::string const fatbinaryOutputRel =
  1491. cmStrCat(relPath, relObjectDir, "cmake_cuda_fatbin.h");
  1492. localGen->WriteMakeRule(*this->BuildFileStream, nullptr, fatbinaryOutputRel,
  1493. fatbinaryDepends, { fatbinaryCommand }, false);
  1494. // Compile the stub that registers the kernels and contains the
  1495. // fatbinaries.
  1496. cmRulePlaceholderExpander::RuleVariables vars;
  1497. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  1498. vars.CMTargetType =
  1499. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  1500. vars.CMTargetLabels = this->GeneratorTarget->GetTargetLabelsString().c_str();
  1501. vars.Language = "CUDA";
  1502. vars.Object = output.c_str();
  1503. vars.Fatbinary = fatbinaryOutput.c_str();
  1504. vars.RegisterFile = registerFile.c_str();
  1505. vars.Config = this->GetConfigName().c_str();
  1506. std::string linkFlags;
  1507. this->GetDeviceLinkFlags(linkFlags, "CUDA");
  1508. vars.LinkFlags = linkFlags.c_str();
  1509. std::string const flags = this->GetFlags("CUDA", this->GetConfigName());
  1510. vars.Flags = flags.c_str();
  1511. std::string compileCmd = this->GetLinkRule("CMAKE_CUDA_DEVICE_LINK_COMPILE");
  1512. auto rulePlaceholderExpander = localGen->CreateRulePlaceholderExpander(
  1513. cmBuildStep::Link, this->GetGeneratorTarget(), "CUDA");
  1514. rulePlaceholderExpander->ExpandRuleVariables(localGen, compileCmd, vars);
  1515. commands.emplace_back(compileCmd);
  1516. localGen->WriteMakeRule(*this->BuildFileStream, nullptr, output,
  1517. { fatbinaryOutputRel }, commands, false);
  1518. // Clean all the possible executable names and symlinks.
  1519. this->CleanFiles.insert(cleanFiles.begin(), cleanFiles.end());
  1520. }
  1521. void cmMakefileTargetGenerator::GenerateCustomRuleFile(
  1522. cmCustomCommandGenerator const& ccg)
  1523. {
  1524. // Collect the commands.
  1525. std::vector<std::string> commands;
  1526. std::string comment = this->LocalGenerator->ConstructComment(ccg);
  1527. if (!comment.empty()) {
  1528. // add in a progress call if needed
  1529. this->NumberOfProgressActions++;
  1530. if (!this->NoRuleMessages) {
  1531. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  1532. this->MakeEchoProgress(progress);
  1533. this->LocalGenerator->AppendEcho(
  1534. commands, comment, cmLocalUnixMakefileGenerator3::EchoGenerate,
  1535. &progress);
  1536. }
  1537. }
  1538. // Now append the actual user-specified commands.
  1539. std::ostringstream content;
  1540. this->LocalGenerator->AppendCustomCommand(
  1541. commands, ccg, this->GeneratorTarget,
  1542. this->LocalGenerator->GetBinaryDirectory(), false, &content);
  1543. // Collect the dependencies.
  1544. std::vector<std::string> depends;
  1545. this->LocalGenerator->AppendCustomDepend(depends, ccg);
  1546. if (!ccg.GetCC().GetDepfile().empty()) {
  1547. // Add dependency over timestamp file for dependencies management
  1548. auto dependTimestamp = this->LocalGenerator->MaybeRelativeToTopBinDir(
  1549. cmStrCat(this->TargetBuildDirectoryFull, "/compiler_depend.ts"));
  1550. depends.emplace_back(std::move(dependTimestamp));
  1551. }
  1552. // Write the rule.
  1553. std::vector<std::string> const& outputs = ccg.GetOutputs();
  1554. bool const symbolic = this->WriteMakeRule(*this->BuildFileStream, nullptr,
  1555. outputs, depends, commands);
  1556. // Symbolic inputs are not expected to exist, so add dummy rules.
  1557. if (this->CMP0113New && !depends.empty()) {
  1558. std::vector<std::string> no_depends;
  1559. std::vector<std::string> no_commands;
  1560. for (std::string const& dep : depends) {
  1561. if (cmSourceFile* dsf =
  1562. this->Makefile->GetSource(dep, cmSourceFileLocationKind::Known)) {
  1563. if (dsf->GetPropertyAsBool("SYMBOLIC")) {
  1564. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1565. dep, no_depends, no_commands,
  1566. true);
  1567. }
  1568. }
  1569. }
  1570. }
  1571. // If the rule has changed make sure the output is rebuilt.
  1572. if (!symbolic) {
  1573. this->GlobalGenerator->AddRuleHash(ccg.GetOutputs(), content.str());
  1574. }
  1575. // Setup implicit dependency scanning.
  1576. for (auto const& idi : ccg.GetCC().GetImplicitDepends()) {
  1577. std::string objFullPath = cmSystemTools::CollapseFullPath(
  1578. outputs[0], this->LocalGenerator->GetCurrentBinaryDirectory());
  1579. std::string srcFullPath = cmSystemTools::CollapseFullPath(
  1580. idi.second, this->LocalGenerator->GetCurrentBinaryDirectory());
  1581. this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, idi.first,
  1582. objFullPath, srcFullPath);
  1583. }
  1584. // Setup implicit depend for depfile if any
  1585. if (!ccg.GetCC().GetDepfile().empty()) {
  1586. std::string objFullPath = cmSystemTools::CollapseFullPath(
  1587. outputs[0], this->LocalGenerator->GetCurrentBinaryDirectory());
  1588. this->LocalGenerator->AddImplicitDepends(
  1589. this->GeneratorTarget, "CUSTOM", objFullPath, ccg.GetFullDepfile(),
  1590. cmDependencyScannerKind::Compiler);
  1591. }
  1592. this->CustomCommandOutputs.insert(outputs.begin(), outputs.end());
  1593. }
  1594. void cmMakefileTargetGenerator::MakeEchoProgress(
  1595. cmLocalUnixMakefileGenerator3::EchoProgress& progress) const
  1596. {
  1597. progress.Dir =
  1598. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), "/CMakeFiles");
  1599. std::ostringstream progressArg;
  1600. progressArg << "$(CMAKE_PROGRESS_" << this->NumberOfProgressActions << ")";
  1601. progress.Arg = progressArg.str();
  1602. }
  1603. void cmMakefileTargetGenerator::WriteObjectsVariable(
  1604. std::string& variableName, std::string& variableNameExternal,
  1605. bool useWatcomQuote)
  1606. {
  1607. // Write a make variable assignment that lists all objects for the
  1608. // target.
  1609. variableName = this->LocalGenerator->CreateMakeVariable(
  1610. this->GeneratorTarget->GetName(), "_OBJECTS");
  1611. *this->BuildFileStream << "# Object files for target "
  1612. << this->GeneratorTarget->GetName() << "\n"
  1613. << variableName << " =";
  1614. auto const& lineContinue = this->GlobalGenerator->LineContinueDirective;
  1615. cmValue pchExtension = this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  1616. for (std::string const& obj : this->Objects) {
  1617. if (cmHasSuffix(obj, pchExtension)) {
  1618. continue;
  1619. }
  1620. *this->BuildFileStream << " " << lineContinue;
  1621. *this->BuildFileStream
  1622. << cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1623. obj, useWatcomQuote);
  1624. }
  1625. *this->BuildFileStream << "\n";
  1626. // Write a make variable assignment that lists all external objects
  1627. // for the target.
  1628. variableNameExternal = this->LocalGenerator->CreateMakeVariable(
  1629. this->GeneratorTarget->GetName(), "_EXTERNAL_OBJECTS");
  1630. /* clang-format off */
  1631. *this->BuildFileStream
  1632. << "\n"
  1633. << "# External object files for target "
  1634. << this->GeneratorTarget->GetName() << "\n"
  1635. << variableNameExternal << " =";
  1636. /* clang-format on */
  1637. for (std::string const& obj : this->ExternalObjects) {
  1638. *this->BuildFileStream << " " << lineContinue;
  1639. *this->BuildFileStream
  1640. << cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1641. obj, useWatcomQuote);
  1642. }
  1643. *this->BuildFileStream << "\n"
  1644. << "\n";
  1645. }
  1646. class cmMakefileTargetGeneratorObjectStrings
  1647. {
  1648. public:
  1649. cmMakefileTargetGeneratorObjectStrings(std::vector<std::string>& strings,
  1650. cmOutputConverter* outputConverter,
  1651. bool useWatcomQuote,
  1652. cmStateDirectory const& stateDir,
  1653. std::string::size_type limit)
  1654. : Strings(strings)
  1655. , OutputConverter(outputConverter)
  1656. , UseWatcomQuote(useWatcomQuote)
  1657. , StateDir(stateDir)
  1658. , LengthLimit(limit)
  1659. {
  1660. this->Space = "";
  1661. }
  1662. void Feed(std::string const& obj)
  1663. {
  1664. // Construct the name of the next object.
  1665. this->NextObject = this->OutputConverter->ConvertToOutputFormat(
  1666. this->OutputConverter->MaybeRelativeToCurBinDir(obj),
  1667. cmOutputConverter::RESPONSE, this->UseWatcomQuote);
  1668. // Roll over to next string if the limit will be exceeded.
  1669. if (this->LengthLimit != std::string::npos &&
  1670. (this->CurrentString.length() + 1 + this->NextObject.length() >
  1671. this->LengthLimit)) {
  1672. this->Strings.push_back(this->CurrentString);
  1673. this->CurrentString.clear();
  1674. this->Space = "";
  1675. }
  1676. // Separate from previous object.
  1677. this->CurrentString += this->Space;
  1678. this->Space = " ";
  1679. // Append this object.
  1680. this->CurrentString += this->NextObject;
  1681. }
  1682. void Done() { this->Strings.push_back(this->CurrentString); }
  1683. private:
  1684. std::vector<std::string>& Strings;
  1685. cmOutputConverter* OutputConverter;
  1686. bool UseWatcomQuote;
  1687. cmStateDirectory StateDir;
  1688. std::string::size_type LengthLimit;
  1689. std::string CurrentString;
  1690. std::string NextObject;
  1691. char const* Space;
  1692. };
  1693. void cmMakefileTargetGenerator::WriteObjectsStrings(
  1694. std::vector<std::string>& objStrings, bool useWatcomQuote,
  1695. std::string::size_type limit)
  1696. {
  1697. cmValue pchExtension = this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  1698. cmMakefileTargetGeneratorObjectStrings helper(
  1699. objStrings, this->LocalGenerator, useWatcomQuote,
  1700. this->LocalGenerator->GetStateSnapshot().GetDirectory(), limit);
  1701. for (std::string const& obj : this->Objects) {
  1702. if (cmHasSuffix(obj, pchExtension)) {
  1703. continue;
  1704. }
  1705. helper.Feed(obj);
  1706. }
  1707. for (std::string const& obj : this->ExternalObjects) {
  1708. helper.Feed(obj);
  1709. }
  1710. auto const ispcAdditionalObjs =
  1711. this->GeneratorTarget->GetGeneratedISPCObjects(this->GetConfigName());
  1712. for (std::string const& obj : ispcAdditionalObjs) {
  1713. helper.Feed(obj);
  1714. }
  1715. helper.Done();
  1716. }
  1717. void cmMakefileTargetGenerator::WriteTargetDriverRule(
  1718. std::string const& main_output, bool relink)
  1719. {
  1720. // Compute the name of the driver target.
  1721. std::string dir =
  1722. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget);
  1723. std::string buildTargetRuleName =
  1724. cmStrCat(std::move(dir), relink ? "/preinstall" : "/build");
  1725. buildTargetRuleName =
  1726. this->LocalGenerator->MaybeRelativeToTopBinDir(buildTargetRuleName);
  1727. // Build the list of target outputs to drive.
  1728. std::vector<std::string> depends{ main_output };
  1729. char const* comment = nullptr;
  1730. if (relink) {
  1731. // Setup the comment for the preinstall driver.
  1732. comment = "Rule to relink during preinstall.";
  1733. } else {
  1734. // Setup the comment for the main build driver.
  1735. comment = "Rule to build all files generated by this target.";
  1736. // Make sure all custom command outputs in this target are built.
  1737. if (this->CustomCommandDriver == OnBuild) {
  1738. this->DriveCustomCommands(depends);
  1739. }
  1740. // Make sure the extra files are built.
  1741. cm::append(depends, this->ExtraFiles);
  1742. }
  1743. // Write the driver rule.
  1744. std::vector<std::string> no_commands;
  1745. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, comment,
  1746. buildTargetRuleName, depends,
  1747. no_commands, true);
  1748. }
  1749. void cmMakefileTargetGenerator::AppendTargetDepends(
  1750. std::vector<std::string>& depends, bool ignoreType)
  1751. {
  1752. // Static libraries never depend on anything for linking.
  1753. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY &&
  1754. !ignoreType) {
  1755. return;
  1756. }
  1757. std::string const& cfg = this->GetConfigName();
  1758. if (this->GeneratorTarget->HasLinkDependencyFile(cfg)) {
  1759. depends.push_back(
  1760. cmStrCat(this->TargetBuildDirectoryFull, "/compiler_depend.ts"));
  1761. }
  1762. // Loop over all library dependencies.
  1763. if (cmComputeLinkInformation const* cli =
  1764. this->GeneratorTarget->GetLinkInformation(cfg)) {
  1765. cm::append(depends, cli->GetDepends());
  1766. }
  1767. }
  1768. void cmMakefileTargetGenerator::AppendObjectDepends(
  1769. std::vector<std::string>& depends)
  1770. {
  1771. // Add dependencies on the compiled object files.
  1772. std::string const& relPath =
  1773. this->LocalGenerator->GetHomeRelativeOutputPath();
  1774. for (std::string const& obj : this->Objects) {
  1775. std::string objTarget = cmStrCat(relPath, obj);
  1776. depends.push_back(std::move(objTarget));
  1777. }
  1778. // Add dependencies on the external object files.
  1779. cm::append(depends, this->ExternalObjects);
  1780. // Add a dependency on the rule file itself.
  1781. this->LocalGenerator->AppendRuleDepend(depends,
  1782. this->BuildFileNameFull.c_str());
  1783. }
  1784. void cmMakefileTargetGenerator::AppendLinkDepends(
  1785. std::vector<std::string>& depends, std::string const& linkLanguage)
  1786. {
  1787. this->AppendObjectDepends(depends);
  1788. // Add dependencies on targets that must be built first.
  1789. this->AppendTargetDepends(depends);
  1790. // Add a dependency on the link definitions file, if any.
  1791. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1792. this->GeneratorTarget->GetModuleDefinitionInfo(
  1793. this->GetConfigName())) {
  1794. for (cmSourceFile const* src : mdi->Sources) {
  1795. depends.push_back(src->GetFullPath());
  1796. }
  1797. }
  1798. // Add a dependency on user-specified manifest files, if any.
  1799. std::vector<cmSourceFile const*> manifest_srcs;
  1800. this->GeneratorTarget->GetManifests(manifest_srcs, this->GetConfigName());
  1801. for (cmSourceFile const* manifest_src : manifest_srcs) {
  1802. depends.push_back(manifest_src->GetFullPath());
  1803. }
  1804. // Add user-specified dependencies.
  1805. this->GeneratorTarget->GetLinkDepends(depends, this->GetConfigName(),
  1806. linkLanguage);
  1807. }
  1808. std::string cmMakefileTargetGenerator::GetLinkRule(
  1809. std::string const& linkRuleVar)
  1810. {
  1811. std::string linkRule = this->Makefile->GetRequiredDefinition(linkRuleVar);
  1812. if (this->GeneratorTarget->HasImplibGNUtoMS(this->GetConfigName())) {
  1813. std::string ruleVar =
  1814. cmStrCat("CMAKE_",
  1815. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName()),
  1816. "_GNUtoMS_RULE");
  1817. if (cmValue rule = this->Makefile->GetDefinition(ruleVar)) {
  1818. linkRule += *rule;
  1819. }
  1820. }
  1821. return linkRule;
  1822. }
  1823. void cmMakefileTargetGenerator::CloseFileStreams()
  1824. {
  1825. this->BuildFileStream.reset();
  1826. this->InfoFileStream.reset();
  1827. this->FlagFileStream.reset();
  1828. }
  1829. void cmMakefileTargetGenerator::CreateLinkScript(
  1830. char const* name, std::vector<std::string> const& link_commands,
  1831. std::vector<std::string>& makefile_commands,
  1832. std::vector<std::string>& makefile_depends)
  1833. {
  1834. // Create the link script file.
  1835. std::string linkScriptName =
  1836. cmStrCat(this->TargetBuildDirectoryFull, '/', name);
  1837. cmGeneratedFileStream linkScriptStream(linkScriptName);
  1838. linkScriptStream.SetCopyIfDifferent(true);
  1839. for (std::string const& link_command : link_commands) {
  1840. // Do not write out empty commands or commands beginning in the
  1841. // shell no-op ":".
  1842. if (!link_command.empty() && link_command[0] != ':') {
  1843. linkScriptStream << link_command << "\n";
  1844. }
  1845. }
  1846. // Create the makefile command to invoke the link script.
  1847. std::string link_command =
  1848. cmStrCat("$(CMAKE_COMMAND) -E cmake_link_script ",
  1849. this->LocalGenerator->ConvertToOutputFormat(
  1850. this->LocalGenerator->MaybeRelativeToCurBinDir(linkScriptName),
  1851. cmOutputConverter::SHELL),
  1852. " --verbose=$(VERBOSE)");
  1853. makefile_commands.push_back(std::move(link_command));
  1854. makefile_depends.push_back(std::move(linkScriptName));
  1855. }
  1856. bool cmMakefileTargetGenerator::CheckUseResponseFileForObjects(
  1857. std::string const& l) const
  1858. {
  1859. // Check for an explicit setting one way or the other.
  1860. std::string const responseVar =
  1861. "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_OBJECTS";
  1862. if (cmValue val = this->Makefile->GetDefinition(responseVar)) {
  1863. if (!val->empty()) {
  1864. return val.IsOn();
  1865. }
  1866. }
  1867. // Check for a system limit.
  1868. if (size_t const limit = cmSystemTools::CalculateCommandLineLengthLimit()) {
  1869. // Compute the total length of our list of object files with room
  1870. // for argument separation and quoting. This does not convert paths
  1871. // relative to CMAKE_CURRENT_BINARY_DIR like the final list will be, so
  1872. // the actual list will likely be much shorter than this. However, in
  1873. // the worst case all objects will remain as absolute paths.
  1874. size_t length = 0;
  1875. for (std::string const& obj : this->Objects) {
  1876. length += obj.size() + 3;
  1877. }
  1878. for (std::string const& ext_obj : this->ExternalObjects) {
  1879. length += ext_obj.size() + 3;
  1880. }
  1881. // We need to guarantee room for both objects and libraries, so
  1882. // if the objects take up more than half then use a response file
  1883. // for them.
  1884. if (length > (limit / 2)) {
  1885. return true;
  1886. }
  1887. }
  1888. // We do not need a response file for objects.
  1889. return false;
  1890. }
  1891. bool cmMakefileTargetGenerator::CheckUseResponseFileForLibraries(
  1892. std::string const& l) const
  1893. {
  1894. // Check for an explicit setting one way or the other.
  1895. std::string const responseVar =
  1896. "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_LIBRARIES";
  1897. if (cmValue val = this->Makefile->GetDefinition(responseVar)) {
  1898. if (!val->empty()) {
  1899. return val.IsOn();
  1900. }
  1901. }
  1902. // We do not need a response file for libraries.
  1903. return false;
  1904. }
  1905. std::string cmMakefileTargetGenerator::CreateResponseFile(
  1906. std::string const& name, std::string const& options,
  1907. std::vector<std::string>& makefile_depends, std::string const& language)
  1908. {
  1909. // FIXME: Find a better way to determine the response file encoding,
  1910. // perhaps using tool-specific platform information variables.
  1911. // For now, use the makefile encoding as a heuristic.
  1912. codecvt_Encoding responseEncoding =
  1913. this->GlobalGenerator->GetMakefileEncoding();
  1914. // Non-MSVC tooling doesn't understand BOM encoded files.
  1915. if (responseEncoding == codecvt_Encoding::UTF8_WITH_BOM &&
  1916. (language == "CUDA" || !this->Makefile->IsOn("MSVC"))) {
  1917. responseEncoding = codecvt_Encoding::UTF8;
  1918. }
  1919. // Create the response file.
  1920. std::string responseFileNameFull =
  1921. cmStrCat(this->TargetBuildDirectoryFull, '/', name);
  1922. cmGeneratedFileStream responseStream(responseFileNameFull, false,
  1923. responseEncoding);
  1924. responseStream.SetCopyIfDifferent(true);
  1925. responseStream << options << "\n";
  1926. // Add a dependency so the target will rebuild when the set of
  1927. // objects changes.
  1928. makefile_depends.push_back(std::move(responseFileNameFull));
  1929. // Construct the name to be used on the command line.
  1930. std::string responseFileName =
  1931. cmStrCat(this->TargetBuildDirectory, '/', name);
  1932. return responseFileName;
  1933. }
  1934. std::unique_ptr<cmLinkLineComputer>
  1935. cmMakefileTargetGenerator::CreateLinkLineComputer(
  1936. cmOutputConverter* outputConverter, cmStateDirectory const& stateDir)
  1937. {
  1938. if (this->Makefile->IsOn("MSVC60")) {
  1939. return this->GlobalGenerator->CreateMSVC60LinkLineComputer(outputConverter,
  1940. stateDir);
  1941. }
  1942. return this->GlobalGenerator->CreateLinkLineComputer(outputConverter,
  1943. stateDir);
  1944. }
  1945. void cmMakefileTargetGenerator::CreateLinkLibs(
  1946. cmLinkLineComputer* linkLineComputer, std::string& linkLibs,
  1947. bool useResponseFile, std::vector<std::string>& makefile_depends,
  1948. std::string const& linkLanguage, ResponseFlagFor responseMode)
  1949. {
  1950. if (cmComputeLinkInformation* pcli =
  1951. this->GeneratorTarget->GetLinkInformation(this->GetConfigName())) {
  1952. std::string frameworkPath;
  1953. std::string linkPath;
  1954. this->LocalGenerator->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1955. frameworkPath, linkPath);
  1956. linkLibs = frameworkPath + linkPath + linkLibs;
  1957. }
  1958. if (useResponseFile &&
  1959. linkLibs.find_first_not_of(' ') != std::string::npos) {
  1960. // Lookup the response file reference flag.
  1961. std::string responseFlag = this->GetResponseFlag(responseMode);
  1962. // Create this response file.
  1963. std::string const responseFileName =
  1964. (responseMode == Link) ? "linkLibs.rsp" : "deviceLinkLibs.rsp";
  1965. std::string const responseLang =
  1966. (responseMode == Link) ? linkLanguage : "CUDA";
  1967. std::string link_rsp = this->CreateResponseFile(
  1968. responseFileName, linkLibs, makefile_depends, responseLang);
  1969. // Reference the response file.
  1970. linkLibs = cmStrCat(std::move(responseFlag),
  1971. this->LocalGenerator->ConvertToOutputFormat(
  1972. std::move(link_rsp), cmOutputConverter::SHELL));
  1973. }
  1974. }
  1975. void cmMakefileTargetGenerator::CreateObjectLists(
  1976. bool useLinkScript, bool useArchiveRules, bool useResponseFile,
  1977. std::string& buildObjs, std::vector<std::string>& makefile_depends,
  1978. bool useWatcomQuote, std::string const& linkLanguage,
  1979. ResponseFlagFor responseMode)
  1980. {
  1981. std::string variableName;
  1982. std::string variableNameExternal;
  1983. this->WriteObjectsVariable(variableName, variableNameExternal,
  1984. useWatcomQuote);
  1985. if (useResponseFile) {
  1986. // MSVC response files cannot exceed 128K.
  1987. std::string::size_type constexpr responseFileLimit = 131000;
  1988. // Construct the individual object list strings.
  1989. std::vector<std::string> object_strings;
  1990. this->WriteObjectsStrings(object_strings, useWatcomQuote,
  1991. responseFileLimit);
  1992. // Lookup the response file reference flag.
  1993. std::string const responseFlag = this->GetResponseFlag(responseMode);
  1994. // Write a response file for each string.
  1995. char const* sep = "";
  1996. for (unsigned int i = 0; i < object_strings.size(); ++i) {
  1997. // Number the response files.
  1998. std::string responseFileName = cmStrCat(
  1999. (responseMode == Link) ? "objects" : "deviceObjects", i + 1, ".rsp");
  2000. // Create this response file.
  2001. std::string objects_rsp = this->CreateResponseFile(
  2002. responseFileName, object_strings[i], makefile_depends, linkLanguage);
  2003. buildObjs +=
  2004. cmStrCat(sep, // Separate from previous response file references.
  2005. responseFlag, // Reference the response file.
  2006. this->LocalGenerator->ConvertToOutputFormat(
  2007. objects_rsp, cmOutputConverter::SHELL));
  2008. sep = " ";
  2009. }
  2010. } else if (useLinkScript) {
  2011. if (!useArchiveRules) {
  2012. std::vector<std::string> objStrings;
  2013. this->WriteObjectsStrings(objStrings, useWatcomQuote);
  2014. buildObjs = objStrings[0];
  2015. }
  2016. } else {
  2017. buildObjs =
  2018. cmStrCat("$(", variableName, ") $(", variableNameExternal, ')');
  2019. }
  2020. }
  2021. void cmMakefileTargetGenerator::AddIncludeFlags(std::string& flags,
  2022. std::string const& lang,
  2023. std::string const& /*config*/)
  2024. {
  2025. std::string const responseVar =
  2026. cmStrCat("CMAKE_", lang, "_USE_RESPONSE_FILE_FOR_INCLUDES");
  2027. bool const useResponseFile = this->Makefile->IsOn(responseVar);
  2028. std::vector<std::string> includes;
  2029. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  2030. lang, this->GetConfigName());
  2031. std::string const includeFlags = this->LocalGenerator->GetIncludeFlags(
  2032. includes, this->GeneratorTarget, lang, this->GetConfigName(),
  2033. useResponseFile);
  2034. if (includeFlags.empty()) {
  2035. return;
  2036. }
  2037. if (useResponseFile) {
  2038. std::string const responseFlagVar =
  2039. "CMAKE_" + lang + "_RESPONSE_FILE_FLAG";
  2040. std::string responseFlag =
  2041. this->Makefile->GetSafeDefinition(responseFlagVar);
  2042. if (responseFlag.empty()) {
  2043. responseFlag = "@";
  2044. }
  2045. std::string const name = cmStrCat("includes_", lang, ".rsp");
  2046. std::string const arg = std::move(responseFlag) +
  2047. this->CreateResponseFile(name, includeFlags, this->FlagFileDepends[lang],
  2048. lang);
  2049. this->LocalGenerator->AppendFlags(flags, arg);
  2050. } else {
  2051. this->LocalGenerator->AppendFlags(flags, includeFlags);
  2052. }
  2053. }
  2054. void cmMakefileTargetGenerator::GenDefFile(
  2055. std::vector<std::string>& real_link_commands)
  2056. {
  2057. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  2058. this->GeneratorTarget->GetModuleDefinitionInfo(this->GetConfigName());
  2059. if (!mdi || !mdi->DefFileGenerated) {
  2060. return;
  2061. }
  2062. std::string cmd = cmSystemTools::GetCMakeCommand();
  2063. cmd = cmStrCat(
  2064. this->LocalGenerator->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL),
  2065. " -E __create_def ",
  2066. this->LocalGenerator->ConvertToOutputFormat(
  2067. this->LocalGenerator->MaybeRelativeToCurBinDir(mdi->DefFile),
  2068. cmOutputConverter::SHELL),
  2069. ' ');
  2070. std::string objlist_file = mdi->DefFile + ".objs";
  2071. cmd += this->LocalGenerator->ConvertToOutputFormat(
  2072. this->LocalGenerator->MaybeRelativeToCurBinDir(objlist_file),
  2073. cmOutputConverter::SHELL);
  2074. cmValue const nm_executable = this->Makefile->GetDefinition("CMAKE_NM");
  2075. if (cmNonempty(nm_executable)) {
  2076. cmd += " --nm=";
  2077. cmd += this->LocalCommonGenerator->ConvertToOutputFormat(
  2078. *nm_executable, cmOutputConverter::SHELL);
  2079. }
  2080. real_link_commands.insert(real_link_commands.begin(), cmd);
  2081. // create a list of obj files for the -E __create_def to read
  2082. cmGeneratedFileStream fout(objlist_file);
  2083. if (mdi->WindowsExportAllSymbols) {
  2084. for (std::string const& obj : this->Objects) {
  2085. if (cmHasLiteralSuffix(obj, ".obj")) {
  2086. fout << obj << "\n";
  2087. }
  2088. }
  2089. for (std::string const& obj : this->ExternalObjects) {
  2090. fout << obj << "\n";
  2091. }
  2092. }
  2093. for (cmSourceFile const* src : mdi->Sources) {
  2094. fout << src->GetFullPath() << "\n";
  2095. }
  2096. }
  2097. std::string cmMakefileTargetGenerator::GetResponseFlag(
  2098. ResponseFlagFor mode) const
  2099. {
  2100. std::string responseFlag = "@";
  2101. std::string responseFlagVar;
  2102. auto const lang =
  2103. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
  2104. if (mode == cmMakefileTargetGenerator::ResponseFlagFor::Link) {
  2105. responseFlagVar = cmStrCat("CMAKE_", lang, "_RESPONSE_FILE_LINK_FLAG");
  2106. } else if (mode == cmMakefileTargetGenerator::ResponseFlagFor::DeviceLink) {
  2107. responseFlagVar = "CMAKE_CUDA_RESPONSE_FILE_DEVICE_LINK_FLAG";
  2108. }
  2109. if (cmValue const p = this->Makefile->GetDefinition(responseFlagVar)) {
  2110. responseFlag = *p;
  2111. }
  2112. return responseFlag;
  2113. }