cmMakefileTargetGenerator.cxx 85 KB

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