cmMakefileTargetGenerator.cxx 88 KB

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