cmFastbuildNormalTargetGenerator.cxx 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmFastbuildNormalTargetGenerator.h"
  4. #include <algorithm>
  5. #include <cstddef>
  6. #include <iterator>
  7. #include <map>
  8. #include <sstream>
  9. #include <string>
  10. #include <unordered_map>
  11. #include <unordered_set>
  12. #include <utility>
  13. #include <cm/memory>
  14. #include <cm/optional>
  15. #include "cmsys/FStream.hxx"
  16. #include "cmAlgorithms.h"
  17. #include "cmCommonTargetGenerator.h"
  18. #include "cmCryptoHash.h"
  19. #include "cmFastbuildTargetGenerator.h"
  20. #include "cmGeneratedFileStream.h"
  21. #include "cmGeneratorExpression.h"
  22. #include "cmGeneratorTarget.h"
  23. #include "cmGlobalCommonGenerator.h"
  24. #include "cmGlobalFastbuildGenerator.h"
  25. #include "cmLinkLineComputer.h"
  26. #include "cmList.h"
  27. #include "cmListFileCache.h"
  28. #include "cmLocalCommonGenerator.h"
  29. #include "cmLocalFastbuildGenerator.h"
  30. #include "cmLocalGenerator.h"
  31. #include "cmMakefile.h"
  32. #include "cmOSXBundleGenerator.h"
  33. #include "cmObjectLocation.h"
  34. #include "cmOutputConverter.h"
  35. #include "cmSourceFile.h"
  36. #include "cmState.h"
  37. #include "cmStateDirectory.h"
  38. #include "cmStateSnapshot.h"
  39. #include "cmStateTypes.h"
  40. #include "cmStringAlgorithms.h"
  41. #include "cmSystemTools.h"
  42. #include "cmTarget.h"
  43. #include "cmTargetDepend.h"
  44. #include "cmValue.h"
  45. #include "cmake.h"
  46. namespace {
  47. std::string const COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  48. std::string const COMPILE_OPTIONS("COMPILE_OPTIONS");
  49. std::string const COMPILE_FLAGS("COMPILE_FLAGS");
  50. std::string const CMAKE_LANGUAGE("CMAKE");
  51. std::string const INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  52. std::string const CMAKE_UNITY_BUILD("CMAKE_UNITY_BUILD");
  53. std::string const CMAKE_UNITY_BUILD_BATCH_SIZE("CMAKE_UNITY_BUILD_BATCH_SIZE");
  54. std::string const UNITY_BUILD("UNITY_BUILD");
  55. std::string const UNITY_BUILD_BATCH_SIZE("UNITY_BUILD_BATCH_SIZE");
  56. std::string const SKIP_UNITY_BUILD_INCLUSION("SKIP_UNITY_BUILD_INCLUSION");
  57. std::string const UNITY_GROUP("UNITY_GROUP");
  58. } // anonymous namespace
  59. cmFastbuildNormalTargetGenerator::cmFastbuildNormalTargetGenerator(
  60. cmGeneratorTarget* gt, std::string configParam)
  61. : cmFastbuildTargetGenerator(gt, std::move(configParam))
  62. , RulePlaceholderExpander(
  63. this->LocalCommonGenerator->CreateRulePlaceholderExpander())
  64. , ObjectOutDir(this->GetGlobalGenerator()->ConvertToFastbuildPath(
  65. this->GeneratorTarget->GetObjectDirectory(Config)))
  66. , Languages(GetLanguages())
  67. , CompileObjectCmakeRules(GetCompileObjectCommand())
  68. {
  69. LogMessage(cmStrCat("objectOutDir: ", ObjectOutDir));
  70. this->OSXBundleGenerator = cm::make_unique<cmOSXBundleGenerator>(gt);
  71. this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders);
  72. // Quotes to account for potential spaces.
  73. RulePlaceholderExpander->SetTargetImpLib(
  74. "\"" FASTBUILD_DOLLAR_TAG "TargetOutputImplib" FASTBUILD_DOLLAR_TAG "\"");
  75. for (auto const& lang : Languages) {
  76. TargetIncludesByLanguage[lang] = this->GetIncludes(lang, Config);
  77. LogMessage("targetIncludes for lang " + lang + " = " +
  78. TargetIncludesByLanguage[lang]);
  79. for (auto const& arch : this->GetArches()) {
  80. auto& flags = CompileFlagsByLangAndArch[std::make_pair(lang, arch)];
  81. this->LocalCommonGenerator->GetTargetCompileFlags(
  82. this->GeneratorTarget, Config, lang, flags, arch);
  83. LogMessage(
  84. cmStrCat("Lang: ", lang, ", arch: ", arch, ", flags: ", flags));
  85. }
  86. }
  87. }
  88. std::string cmFastbuildNormalTargetGenerator::DetectCompilerFlags(
  89. cmSourceFile const& srcFile, std::string const& arch)
  90. {
  91. std::string const language = srcFile.GetLanguage();
  92. cmGeneratorExpressionInterpreter genexInterpreter(
  93. this->GetLocalGenerator(), Config, this->GeneratorTarget, language);
  94. std::vector<std::string> sourceIncludesVec;
  95. if (cmValue cincludes = srcFile.GetProperty(INCLUDE_DIRECTORIES)) {
  96. this->LocalGenerator->AppendIncludeDirectories(
  97. sourceIncludesVec,
  98. genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES), srcFile);
  99. }
  100. std::string sourceIncludesStr = this->LocalGenerator->GetIncludeFlags(
  101. sourceIncludesVec, this->GeneratorTarget, language, Config, false);
  102. LogMessage(cmStrCat("sourceIncludes = ", sourceIncludesStr));
  103. std::string compileFlags =
  104. CompileFlagsByLangAndArch[std::make_pair(language, arch)];
  105. this->GeneratorTarget->AddExplicitLanguageFlags(compileFlags, srcFile);
  106. if (cmValue const cflags = srcFile.GetProperty(COMPILE_FLAGS)) {
  107. this->LocalGenerator->AppendFlags(
  108. compileFlags, genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  109. }
  110. if (cmValue const coptions = srcFile.GetProperty(COMPILE_OPTIONS)) {
  111. this->LocalGenerator->AppendCompileOptions(
  112. compileFlags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  113. }
  114. // Source includes take precedence over target includes.
  115. this->LocalGenerator->AppendFlags(compileFlags, sourceIncludesStr);
  116. this->LocalGenerator->AppendFlags(compileFlags,
  117. TargetIncludesByLanguage[language]);
  118. if (language == "Fortran") {
  119. this->AppendFortranFormatFlags(compileFlags, srcFile);
  120. this->AppendFortranPreprocessFlags(compileFlags, srcFile);
  121. }
  122. LogMessage(cmStrCat("compileFlags = ", compileFlags));
  123. return compileFlags;
  124. }
  125. void cmFastbuildNormalTargetGenerator::GetLinkerExecutableAndArgs(
  126. std::string const& command, std::string& outLinkerExecutable,
  127. std::string& outLinkerArgs)
  128. {
  129. if (command.empty()) {
  130. return;
  131. }
  132. LogMessage("Link Command: " + command);
  133. auto const& compilers = this->GetGlobalGenerator()->Compilers;
  134. auto const linkerLauncherVarName = FASTBUILD_LINKER_LAUNCHER_PREFIX +
  135. this->GeneratorTarget->GetLinkerLanguage(Config);
  136. auto const iter = compilers.find(linkerLauncherVarName);
  137. // Tested in "RunCMake.LinkerLauncher" test.
  138. if (iter != compilers.end()) {
  139. LogMessage("Linker launcher: " + iter->first);
  140. outLinkerExecutable = iter->second.Executable;
  141. outLinkerArgs = cmStrCat(iter->second.Args, " ", command);
  142. } else {
  143. #ifdef _WIN32
  144. std::vector<std::string> args;
  145. std::string tmp;
  146. cmSystemTools::SplitProgramFromArgs(command, tmp, outLinkerArgs);
  147. // cmLocalGenerator::GetStaticLibraryFlags seems to add empty quotes when
  148. // appending "STATIC_LIBRARY_FLAGS_DEBUG"...
  149. cmSystemTools::ReplaceString(outLinkerArgs, "\"\"", "");
  150. cmSystemTools::ParseWindowsCommandLine(command.c_str(), args);
  151. outLinkerExecutable = std::move(args[0]);
  152. #else
  153. cmSystemTools::SplitProgramFromArgs(command, outLinkerExecutable,
  154. outLinkerArgs);
  155. #endif
  156. }
  157. LogMessage("Linker Exe: " + outLinkerExecutable);
  158. LogMessage("Linker args: " + outLinkerArgs);
  159. }
  160. bool cmFastbuildNormalTargetGenerator::DetectBaseLinkerCommand(
  161. std::string& command, std::string const& arch,
  162. cmGeneratorTarget::Names const& targetNames)
  163. {
  164. std::string const linkLanguage =
  165. this->GeneratorTarget->GetLinkerLanguage(Config);
  166. if (linkLanguage.empty()) {
  167. cmSystemTools::Error("CMake can not determine linker language for "
  168. "target: " +
  169. this->GeneratorTarget->GetName());
  170. return false;
  171. }
  172. LogMessage("linkLanguage: " + linkLanguage);
  173. std::string linkLibs;
  174. std::string targetFlags;
  175. std::string linkFlags;
  176. std::string frameworkPath;
  177. // Tested in "RunCMake.StandardLinkDirectories" test.
  178. std::string linkPath;
  179. std::unique_ptr<cmLinkLineComputer> const linkLineComputer =
  180. this->GetGlobalGenerator()->CreateLinkLineComputer(
  181. this->LocalGenerator,
  182. this->GetLocalGenerator()->GetStateSnapshot().GetDirectory());
  183. this->LocalCommonGenerator->GetTargetFlags(
  184. linkLineComputer.get(), Config, linkLibs, targetFlags, linkFlags,
  185. frameworkPath, linkPath, this->GeneratorTarget);
  186. // cmLocalGenerator::GetStaticLibraryFlags seems to add empty quotes when
  187. // appending "STATIC_LIBRARY_FLAGS_DEBUG"...
  188. cmSystemTools::ReplaceString(linkFlags, "\"\"", "");
  189. LogMessage("linkLibs: " + linkLibs);
  190. LogMessage("targetFlags: " + targetFlags);
  191. LogMessage("linkFlags: " + linkFlags);
  192. LogMessage("frameworkPath: " + frameworkPath);
  193. LogMessage("linkPath: " + linkPath);
  194. LogMessage("MANIFESTS: " + this->GetManifests(Config));
  195. cmComputeLinkInformation* linkInfo =
  196. this->GeneratorTarget->GetLinkInformation(Config);
  197. if (!linkInfo) {
  198. return false;
  199. }
  200. // Tested in "RunCMake.RuntimePath" test.
  201. std::string const rpath = linkLineComputer->ComputeRPath(*linkInfo);
  202. LogMessage("RPath: " + rpath);
  203. if (!linkFlags.empty()) {
  204. linkFlags += " ";
  205. }
  206. linkFlags += cmJoin({ rpath, frameworkPath, linkPath }, " ");
  207. cmStateEnums::TargetType const targetType = this->GeneratorTarget->GetType();
  208. // Add OS X version flags, if any.
  209. if (targetType == cmStateEnums::SHARED_LIBRARY ||
  210. targetType == cmStateEnums::MODULE_LIBRARY) {
  211. this->AppendOSXVerFlag(linkFlags, linkLanguage, "COMPATIBILITY", true);
  212. this->AppendOSXVerFlag(linkFlags, linkLanguage, "CURRENT", false);
  213. }
  214. // Add Arch flags to link flags for binaries
  215. if (targetType == cmStateEnums::SHARED_LIBRARY ||
  216. targetType == cmStateEnums::MODULE_LIBRARY ||
  217. targetType == cmStateEnums::EXECUTABLE) {
  218. this->LocalCommonGenerator->AddArchitectureFlags(
  219. linkFlags, this->GeneratorTarget, linkLanguage, Config, arch);
  220. this->UseLWYU = this->GetLocalGenerator()->AppendLWYUFlags(
  221. linkFlags, this->GetGeneratorTarget(), linkLanguage);
  222. }
  223. cmRulePlaceholderExpander::RuleVariables vars;
  224. vars.CMTargetName = this->GeneratorTarget->GetName().c_str();
  225. vars.CMTargetType = cmState::GetTargetTypeName(targetType).c_str();
  226. vars.CMTargetLabels =
  227. this->GetGeneratorTarget()->GetTargetLabelsString().c_str();
  228. vars.Config = Config.c_str();
  229. vars.Language = linkLanguage.c_str();
  230. std::string const manifests =
  231. cmJoin(this->GetManifestsAsFastbuildPath(), " ");
  232. vars.Manifests = manifests.c_str();
  233. std::string const stdLibString = this->Makefile->GetSafeDefinition(
  234. cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LIBRARIES"));
  235. LogMessage(cmStrCat("Target type: ", this->GeneratorTarget->GetType()));
  236. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  237. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  238. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  239. vars.Objects = FASTBUILD_1_0_INPUT_PLACEHOLDER;
  240. vars.LinkLibraries = stdLibString.c_str();
  241. } else {
  242. vars.Objects = FASTBUILD_1_INPUT_PLACEHOLDER;
  243. }
  244. vars.ObjectDir = FASTBUILD_DOLLAR_TAG "TargetOutDir" FASTBUILD_DOLLAR_TAG;
  245. vars.Target = FASTBUILD_2_INPUT_PLACEHOLDER;
  246. std::string install_dir;
  247. std::string target_so_name;
  248. if (this->GeneratorTarget->HasSOName(Config)) {
  249. vars.SONameFlag = this->Makefile->GetSONameFlag(
  250. this->GeneratorTarget->GetLinkerLanguage(Config));
  251. target_so_name =
  252. cmGlobalFastbuildGenerator::QuoteIfHasSpaces(targetNames.SharedObject);
  253. vars.TargetSOName = target_so_name.c_str();
  254. // Tested in "RunCMake.RuntimePath / RunCMake.INSTALL_NAME_DIR"
  255. // tests.
  256. install_dir = this->LocalGenerator->ConvertToOutputFormat(
  257. this->GeneratorTarget->GetInstallNameDirForBuildTree(Config),
  258. cmOutputConverter::SHELL);
  259. vars.TargetInstallNameDir = install_dir.c_str();
  260. } else {
  261. vars.TargetSOName = "";
  262. }
  263. vars.TargetPDB = FASTBUILD_DOLLAR_TAG "LinkerPDB" FASTBUILD_DOLLAR_TAG;
  264. // Setup the target version.
  265. std::string targetVersionMajor;
  266. std::string targetVersionMinor;
  267. {
  268. std::ostringstream majorStream;
  269. std::ostringstream minorStream;
  270. int major;
  271. int minor;
  272. this->GeneratorTarget->GetTargetVersion(major, minor);
  273. majorStream << major;
  274. minorStream << minor;
  275. targetVersionMajor = majorStream.str();
  276. targetVersionMinor = minorStream.str();
  277. }
  278. vars.TargetVersionMajor = targetVersionMajor.c_str();
  279. vars.TargetVersionMinor = targetVersionMinor.c_str();
  280. vars.Defines =
  281. FASTBUILD_DOLLAR_TAG "CompileDefineFlags" FASTBUILD_DOLLAR_TAG;
  282. vars.Flags = targetFlags.c_str();
  283. vars.LinkFlags = linkFlags.c_str();
  284. vars.LanguageCompileFlags = "";
  285. std::string const linker = this->GeneratorTarget->GetLinkerTool(Config);
  286. vars.Linker = linker.c_str();
  287. std::string const targetSupportPath = this->ConvertToFastbuildPath(
  288. this->GetGeneratorTarget()->GetCMFSupportDirectory());
  289. vars.TargetSupportDir = targetSupportPath.c_str();
  290. LogMessage("linkFlags: " + linkFlags);
  291. LogMessage("linker: " + linker);
  292. std::string linkRule = GetLinkCommand();
  293. ApplyLinkRuleLauncher(linkRule);
  294. RulePlaceholderExpander->ExpandRuleVariables(
  295. dynamic_cast<cmLocalFastbuildGenerator*>(this->LocalCommonGenerator),
  296. linkRule, vars);
  297. command = std::move(linkRule);
  298. LogMessage(cmStrCat("Expanded link command: ", command));
  299. return true;
  300. }
  301. void cmFastbuildNormalTargetGenerator::ApplyLinkRuleLauncher(
  302. std::string& command)
  303. {
  304. std::string const val = this->GetLocalGenerator()->GetRuleLauncher(
  305. this->GetGeneratorTarget(), "RULE_LAUNCH_LINK", Config);
  306. if (cmNonempty(val)) {
  307. LogMessage("RULE_LAUNCH_LINK: " + val);
  308. command = cmStrCat(val, " ", command);
  309. }
  310. }
  311. void cmFastbuildNormalTargetGenerator::ApplyLWYUToLinkerCommand(
  312. FastbuildLinkerNode& linkerNode)
  313. {
  314. cmValue const lwyuCheck =
  315. this->Makefile->GetDefinition("CMAKE_LINK_WHAT_YOU_USE_CHECK");
  316. if (this->UseLWYU && lwyuCheck) {
  317. LogMessage("UseLWYU=true");
  318. std::string args = " -E __run_co_compile --lwyu=";
  319. args += this->GetLocalGenerator()->EscapeForShell(*lwyuCheck);
  320. args += cmStrCat(
  321. " --source=",
  322. this->ConvertToFastbuildPath(this->GetGeneratorTarget()->GetFullPath(
  323. Config, cmStateEnums::RuntimeBinaryArtifact,
  324. /*realname=*/true)));
  325. LogMessage("LWUY args: " + args);
  326. linkerNode.LinkerStampExe = cmSystemTools::GetCMakeCommand();
  327. linkerNode.LinkerStampExeArgs = std::move(args);
  328. }
  329. }
  330. std::string cmFastbuildNormalTargetGenerator::ComputeDefines(
  331. cmSourceFile const& srcFile)
  332. {
  333. std::string const language = srcFile.GetLanguage();
  334. std::set<std::string> defines;
  335. cmGeneratorExpressionInterpreter genexInterpreter(
  336. this->GetLocalGenerator(), Config, this->GeneratorTarget, language);
  337. if (auto compile_defs = srcFile.GetProperty(COMPILE_DEFINITIONS)) {
  338. this->GetLocalGenerator()->AppendDefines(
  339. defines, genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS));
  340. }
  341. std::string defPropName = "COMPILE_DEFINITIONS_";
  342. defPropName += cmSystemTools::UpperCase(Config);
  343. if (auto config_compile_defs = srcFile.GetProperty(defPropName)) {
  344. this->GetLocalGenerator()->AppendDefines(
  345. defines,
  346. genexInterpreter.Evaluate(*config_compile_defs, COMPILE_DEFINITIONS));
  347. }
  348. std::string definesString = this->GetDefines(language, Config);
  349. LogMessage(cmStrCat("TARGET DEFINES = ", definesString));
  350. this->GetLocalGenerator()->JoinDefines(defines, definesString, language);
  351. LogMessage(cmStrCat("DEFINES = ", definesString));
  352. return definesString;
  353. }
  354. void cmFastbuildNormalTargetGenerator::ComputePCH(
  355. cmSourceFile const& srcFile, FastbuildObjectListNode& node,
  356. std::set<std::string>& createdPCH)
  357. {
  358. if (srcFile.GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  359. return;
  360. }
  361. // We have already computed PCH for this node.
  362. if (!node.PCHOptions.empty() || !node.PCHInputFile.empty() ||
  363. !node.PCHOutputFile.empty()) {
  364. return;
  365. }
  366. std::string const language = srcFile.GetLanguage();
  367. cmGeneratorExpressionInterpreter genexInterpreter(
  368. this->GetLocalGenerator(), Config, this->GeneratorTarget, language);
  369. //.cxx
  370. std::string const pchSource =
  371. this->GeneratorTarget->GetPchSource(Config, language);
  372. //.hxx
  373. std::string const pchHeader =
  374. this->GeneratorTarget->GetPchHeader(Config, language);
  375. //.pch
  376. std::string const pchFile =
  377. this->GeneratorTarget->GetPchFile(Config, language);
  378. if (pchHeader.empty() || pchFile.empty()) {
  379. return;
  380. }
  381. // In "RunCMake.GenEx-TARGET_PROPERTY" test we call set
  382. // CMAKE_PCH_EXTENSION="", so pchHeader becomes same as pchFile...
  383. if (pchHeader == pchFile) {
  384. LogMessage("pchHeader == pchFile > skipping");
  385. LogMessage("pchHeader: " + pchHeader);
  386. LogMessage("pchFile: " + pchFile);
  387. return;
  388. }
  389. node.PCHOutputFile =
  390. this->GetGlobalGenerator()->ConvertToFastbuildPath(pchFile);
  391. // Tell the ObjectList how to use PCH.
  392. std::string const pchUseOption =
  393. this->GeneratorTarget->GetPchUseCompileOptions(Config, language);
  394. LogMessage(cmStrCat("pchUseOption: ", pchUseOption));
  395. std::string origCompileOptions = node.CompilerOptions;
  396. for (auto const& opt :
  397. cmList{ genexInterpreter.Evaluate(pchUseOption, COMPILE_OPTIONS) }) {
  398. node.CompilerOptions += " ";
  399. node.CompilerOptions += opt;
  400. }
  401. if (!createdPCH.emplace(node.PCHOutputFile).second) {
  402. LogMessage(node.PCHOutputFile + " is already created by this target");
  403. return;
  404. }
  405. // Short circuit if the PCH has already been created by another target.
  406. if (!this->GeneratorTarget->GetSafeProperty("PRECOMPILE_HEADERS_REUSE_FROM")
  407. .empty()) {
  408. LogMessage(cmStrCat("PCH: ", node.PCHOutputFile,
  409. " already created by another target"));
  410. return;
  411. }
  412. node.PCHInputFile =
  413. this->GetGlobalGenerator()->ConvertToFastbuildPath(pchSource);
  414. std::string const pchCreateOptions =
  415. this->GeneratorTarget->GetPchCreateCompileOptions(Config, language);
  416. LogMessage(cmStrCat("pchCreateOptions: ", pchCreateOptions));
  417. char const* sep = "";
  418. for (auto const& opt : cmList{
  419. genexInterpreter.Evaluate(pchCreateOptions, COMPILE_OPTIONS) }) {
  420. node.PCHOptions += sep;
  421. node.PCHOptions += opt;
  422. sep = " ";
  423. }
  424. // Reuse compiler options for PCH options.
  425. node.PCHOptions += origCompileOptions;
  426. if (this->Makefile->GetSafeDefinition("CMAKE_" + language +
  427. "_COMPILER_ID") == "MSVC") {
  428. cmSystemTools::ReplaceString(node.PCHOptions,
  429. FASTBUILD_2_INPUT_PLACEHOLDER,
  430. FASTBUILD_3_INPUT_PLACEHOLDER);
  431. }
  432. LogMessage("PCH Source: " + pchSource);
  433. LogMessage("node.PCHInputFile: " + node.PCHInputFile);
  434. LogMessage("node.PCHOutputFile: " + node.PCHOutputFile);
  435. LogMessage("node.PCHOptions: " + node.PCHOptions);
  436. LogMessage("node.CompilerOptions: " + node.CompilerOptions);
  437. }
  438. void cmFastbuildNormalTargetGenerator::EnsureDirectoryExists(
  439. std::string const& path) const
  440. {
  441. if (cmSystemTools::FileIsFullPath(path.c_str())) {
  442. cmSystemTools::MakeDirectory(path.c_str());
  443. } else {
  444. auto* gg = this->GetGlobalGenerator();
  445. std::string fullPath = gg->GetCMakeInstance()->GetHomeOutputDirectory();
  446. // Also ensures there is a trailing slash.
  447. fullPath += path;
  448. cmSystemTools::MakeDirectory(fullPath);
  449. }
  450. }
  451. std::vector<std::string>
  452. cmFastbuildNormalTargetGenerator::GetManifestsAsFastbuildPath() const
  453. {
  454. std::vector<cmSourceFile const*> manifest_srcs;
  455. this->GeneratorTarget->GetManifests(manifest_srcs, Config);
  456. std::vector<std::string> manifests;
  457. manifests.reserve(manifest_srcs.size());
  458. for (auto& manifest_src : manifest_srcs) {
  459. std::string str = this->ConvertToFastbuildPath(
  460. cmSystemTools::ConvertToOutputPath(manifest_src->GetFullPath()));
  461. LogMessage("Manifest: " + str);
  462. manifests.emplace_back(std::move(str));
  463. }
  464. return manifests;
  465. }
  466. void cmFastbuildNormalTargetGenerator::GenerateModuleDefinitionInfo(
  467. FastbuildTarget& target) const
  468. {
  469. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  470. GeneratorTarget->GetModuleDefinitionInfo(Config);
  471. if (mdi && mdi->DefFileGenerated) {
  472. FastbuildExecNode execNode;
  473. execNode.Name = target.Name + "-def-files";
  474. execNode.ExecExecutable = cmSystemTools::GetCMakeCommand();
  475. execNode.ExecArguments =
  476. cmStrCat("-E __create_def ", FASTBUILD_2_INPUT_PLACEHOLDER, " ",
  477. FASTBUILD_1_INPUT_PLACEHOLDER);
  478. std::string const obj_list_file = mdi->DefFile + ".objs";
  479. auto const nm_executable = GetMakefile()->GetDefinition("CMAKE_NM");
  480. if (!nm_executable.IsEmpty()) {
  481. execNode.ExecArguments += " --nm=";
  482. execNode.ExecArguments += ConvertToFastbuildPath(*nm_executable);
  483. }
  484. execNode.ExecOutput = ConvertToFastbuildPath(mdi->DefFile);
  485. execNode.ExecInput.push_back(ConvertToFastbuildPath(obj_list_file));
  486. // RunCMake.AutoExportDll
  487. for (auto const& objList : target.ObjectListNodes) {
  488. execNode.PreBuildDependencies.emplace(objList.Name);
  489. }
  490. // Tested in "RunCMake.AutoExportDll" / "ModuleDefinition" tests.
  491. for (auto& linkerNode : target.LinkerNode) {
  492. linkerNode.Libraries2.emplace_back(execNode.Name);
  493. }
  494. target.PreLinkExecNodes.Nodes.emplace_back(std::move(execNode));
  495. // create a list of obj files for the -E __create_def to read
  496. cmGeneratedFileStream fout(obj_list_file);
  497. // Since we generate this file once during configuration, we should not
  498. // remove it when "clean" is built.
  499. // Tested in "RunCMake.AutoExportDll" / "ModuleDefinition" tests.
  500. this->GetGlobalGenerator()->AllFilesToKeep.insert(obj_list_file);
  501. if (mdi->WindowsExportAllSymbols) {
  502. std::vector<cmSourceFile const*> objectSources;
  503. GeneratorTarget->GetObjectSources(objectSources, Config);
  504. std::map<cmSourceFile const*, cmObjectLocations> mapping;
  505. for (cmSourceFile const* it : objectSources) {
  506. mapping[it];
  507. }
  508. GeneratorTarget->LocalGenerator->ComputeObjectFilenames(mapping, Config,
  509. GeneratorTarget);
  510. std::vector<std::string> objs;
  511. for (cmSourceFile const* it : objectSources) {
  512. auto const& v = mapping[it];
  513. LogMessage("Obj source : " + v.LongLoc.GetPath());
  514. std::string objFile = this->ConvertToFastbuildPath(
  515. GeneratorTarget->GetObjectDirectory(Config) + v.LongLoc.GetPath());
  516. objFile = cmSystemTools::ConvertToOutputPath(objFile);
  517. LogMessage("objFile path: " + objFile);
  518. objs.push_back(objFile);
  519. }
  520. std::vector<cmSourceFile const*> externalObjectSources;
  521. GeneratorTarget->GetExternalObjects(externalObjectSources, Config);
  522. for (cmSourceFile const* it : externalObjectSources) {
  523. objs.push_back(cmSystemTools::ConvertToOutputPath(
  524. this->ConvertToFastbuildPath(it->GetFullPath())));
  525. }
  526. for (std::string const& objFile : objs) {
  527. if (cmHasLiteralSuffix(objFile, ".obj")) {
  528. fout << objFile << "\n";
  529. }
  530. }
  531. }
  532. for (cmSourceFile const* src : mdi->Sources) {
  533. fout << src->GetFullPath() << "\n";
  534. }
  535. }
  536. }
  537. void cmFastbuildNormalTargetGenerator::AddPrebuildDeps(
  538. FastbuildTarget& target) const
  539. {
  540. // All ObjectLists should wait for PRE_BUILD.
  541. for (FastbuildObjectListNode& node : target.ObjectListNodes) {
  542. if (!target.PreBuildExecNodes.Name.empty()) {
  543. node.PreBuildDependencies.emplace(target.PreBuildExecNodes.Name);
  544. }
  545. if (!target.ExecNodes.Name.empty()) {
  546. node.PreBuildDependencies.emplace(target.ExecNodes.Name);
  547. }
  548. }
  549. for (auto& linkerNode : target.LinkerNode) {
  550. // Wait for 'PRE_BUILD' custom commands.
  551. if (!target.PreBuildExecNodes.Name.empty()) {
  552. linkerNode.PreBuildDependencies.emplace(target.PreBuildExecNodes.Name);
  553. }
  554. // Wait for regular custom commands.
  555. if (!target.ExecNodes.Name.empty()) {
  556. linkerNode.PreBuildDependencies.emplace(target.ExecNodes.Name);
  557. }
  558. // All targets that we depend on must be prebuilt.
  559. if (!target.DependenciesAlias.PreBuildDependencies.empty()) {
  560. linkerNode.PreBuildDependencies.emplace(target.DependenciesAlias.Name);
  561. }
  562. }
  563. }
  564. std::set<std::string> cmFastbuildNormalTargetGenerator::GetLanguages()
  565. {
  566. std::set<std::string> result;
  567. this->GetGeneratorTarget()->GetLanguages(result, Config);
  568. for (std::string const& lang : result) {
  569. this->GetGlobalGenerator()->AddCompiler(lang, this->GetMakefile());
  570. }
  571. LogMessage("Languages: " + cmJoin(result, ", "));
  572. return result;
  573. }
  574. std::unordered_map<std::string, std::string>
  575. cmFastbuildNormalTargetGenerator::GetCompileObjectCommand() const
  576. {
  577. std::unordered_map<std::string, std::string> result;
  578. result.reserve(Languages.size());
  579. for (std::string const& lang : Languages) {
  580. std::vector<std::string> commands;
  581. std::string cmakeVar;
  582. if (lang == "CUDA") {
  583. if (this->GeneratorTarget->GetPropertyAsBool(
  584. "CUDA_SEPARABLE_COMPILATION")) {
  585. cmakeVar = "CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION";
  586. } else if (this->GeneratorTarget->GetPropertyAsBool(
  587. "CUDA_PTX_COMPILATION")) {
  588. cmakeVar = "CMAKE_CUDA_COMPILE_PTX_COMPILATION";
  589. } else {
  590. cmakeVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION";
  591. }
  592. } else {
  593. cmakeVar = "CMAKE_";
  594. cmakeVar += lang;
  595. cmakeVar += "_COMPILE_OBJECT";
  596. }
  597. std::string cmakeValue =
  598. LocalCommonGenerator->GetMakefile()->GetSafeDefinition(cmakeVar);
  599. LogMessage(cmakeVar.append(" = ").append(cmakeValue));
  600. result[lang] = std::move(cmakeValue);
  601. }
  602. return result;
  603. }
  604. std::string cmFastbuildNormalTargetGenerator::GetLinkCommand() const
  605. {
  606. std::string const& linkLanguage = GeneratorTarget->GetLinkerLanguage(Config);
  607. std::string linkCmdVar =
  608. GeneratorTarget->GetCreateRuleVariable(linkLanguage, Config);
  609. std::string res = this->Makefile->GetSafeDefinition(linkCmdVar);
  610. if (res.empty() &&
  611. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  612. linkCmdVar = linkCmdVar =
  613. cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_CREATE");
  614. res = this->Makefile->GetSafeDefinition(linkCmdVar);
  615. }
  616. LogMessage("Link rule: " + cmStrCat(linkCmdVar, " = ", res));
  617. return res;
  618. }
  619. void cmFastbuildNormalTargetGenerator::AddCompilerLaunchersForLanguages()
  620. {
  621. // General rule for all languages.
  622. std::string const launchCompile = this->GetLocalGenerator()->GetRuleLauncher(
  623. this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE", Config);
  624. // See if we need to use a compiler launcher like ccache or distcc
  625. for (std::string const& language : Languages) {
  626. std::string const compilerLauncher =
  627. cmCommonTargetGenerator::GetCompilerLauncher(language, Config);
  628. LogMessage("compilerLauncher: " + compilerLauncher);
  629. std::vector<std::string> expanded;
  630. cmExpandList(compilerLauncher, expanded);
  631. if (!expanded.empty()) {
  632. std::string const exe = expanded[0];
  633. expanded.erase(expanded.begin());
  634. this->GetGlobalGenerator()->AddLauncher(FASTBUILD_LAUNCHER_PREFIX, exe,
  635. language, cmJoin(expanded, " "));
  636. } else if (!launchCompile.empty()) {
  637. std::string exe;
  638. std::string args;
  639. cmSystemTools::SplitProgramFromArgs(launchCompile, exe, args);
  640. this->GetGlobalGenerator()->AddLauncher(FASTBUILD_LAUNCHER_PREFIX, exe,
  641. language, args);
  642. }
  643. }
  644. }
  645. void cmFastbuildNormalTargetGenerator::AddLinkerLauncher()
  646. {
  647. std::string const linkerLauncher =
  648. cmCommonTargetGenerator::GetLinkerLauncher(Config);
  649. std::vector<std::string> args;
  650. #ifdef _WIN32
  651. cmSystemTools::ParseWindowsCommandLine(linkerLauncher.c_str(), args);
  652. #else
  653. cmSystemTools::ParseUnixCommandLine(linkerLauncher.c_str(), args);
  654. #endif
  655. if (!args.empty()) {
  656. std::string const exe = std::move(args[0]);
  657. args.erase(args.begin());
  658. this->GetGlobalGenerator()->AddLauncher(
  659. FASTBUILD_LINKER_LAUNCHER_PREFIX, exe,
  660. this->GeneratorTarget->GetLinkerLanguage(Config), cmJoin(args, " "));
  661. }
  662. }
  663. void cmFastbuildNormalTargetGenerator::AddCMakeLauncher()
  664. {
  665. // Add CMake launcher (might be used for static analysis).
  666. this->GetGlobalGenerator()->AddLauncher(FASTBUILD_LAUNCHER_PREFIX,
  667. cmSystemTools::GetCMakeCommand(),
  668. CMAKE_LANGUAGE, "");
  669. }
  670. void cmFastbuildNormalTargetGenerator::ComputePaths(
  671. FastbuildTarget& target) const
  672. {
  673. std::string const objPath = GetGeneratorTarget()->GetSupportDirectory();
  674. EnsureDirectoryExists(objPath);
  675. target.Variables["TargetOutDir"] =
  676. cmSystemTools::ConvertToOutputPath(this->ConvertToFastbuildPath(objPath));
  677. if (GeneratorTarget->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  678. std::string const pdbDir = GeneratorTarget->GetPDBDirectory(Config);
  679. LogMessage("GetPDBDirectory: " + pdbDir);
  680. EnsureDirectoryExists(pdbDir);
  681. std::string const linkerPDB =
  682. cmStrCat(pdbDir, '/', this->GeneratorTarget->GetPDBName(Config));
  683. if (!linkerPDB.empty()) {
  684. target.Variables["LinkerPDB"] = cmSystemTools::ConvertToOutputPath(
  685. this->ConvertToFastbuildPath(linkerPDB));
  686. }
  687. }
  688. if (GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
  689. std::string const pdbDir = GeneratorTarget->GetCompilePDBDirectory(Config);
  690. LogMessage("GetCompilePDBDirectory: " + pdbDir);
  691. EnsureDirectoryExists(pdbDir);
  692. std::string pdbName = this->GeneratorTarget->GetCompilePDBName(Config);
  693. LogMessage("GetCompilePDBName: " + pdbDir);
  694. // If we don't have Compiler's PDB, we must add a trailing slash to satisfy
  695. // MSVC.
  696. bool needTrailingSlash = false;
  697. if (pdbName.empty()) {
  698. needTrailingSlash = true;
  699. }
  700. std::string const compilerPDB = cmStrCat(pdbDir, '\\', pdbName);
  701. if (!compilerPDB.empty()) {
  702. target.Variables["CompilerPDB"] = cmSystemTools::ConvertToOutputPath(
  703. this->ConvertToFastbuildPath(compilerPDB) +
  704. (needTrailingSlash ? "\\ " : ""));
  705. }
  706. }
  707. std::string impLibFile = ConvertToFastbuildPath(
  708. GeneratorTarget->GetFullPath(Config, cmStateEnums::ImportLibraryArtifact));
  709. cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(impLibFile));
  710. if (!impLibFile.empty()) {
  711. cmSystemTools::ConvertToOutputSlashes(impLibFile);
  712. target.Variables["TargetOutputImplib"] = std::move(impLibFile);
  713. }
  714. }
  715. void cmFastbuildNormalTargetGenerator::Generate()
  716. {
  717. this->GeneratorTarget->CheckCxxModuleStatus(Config);
  718. FastbuildTarget fastbuildTarget;
  719. fastbuildTarget.Name = GetTargetName();
  720. fastbuildTarget.BaseName = this->GeneratorTarget->GetName();
  721. LogMessage("<-------------->");
  722. LogMessage("Generate target: " + fastbuildTarget.Name);
  723. LogMessage("Config: " + Config);
  724. LogMessage("Deps: ");
  725. for (cmTargetDepend const& dep : TargetDirectDependencies) {
  726. auto const tname = dep->GetName();
  727. LogMessage(tname);
  728. FastbuildTargetDep targetDep{ tname };
  729. if (dep->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  730. targetDep.Type = FastbuildTargetDepType::ORDER_ONLY;
  731. }
  732. fastbuildTarget.PreBuildDependencies.emplace(std::move(targetDep));
  733. }
  734. ComputePaths(fastbuildTarget);
  735. AddCompilerLaunchersForLanguages();
  736. AddLinkerLauncher();
  737. AddCMakeLauncher();
  738. for (auto& cc : GenerateCommands(FastbuildBuildStep::PRE_BUILD).Nodes) {
  739. fastbuildTarget.PreBuildExecNodes.PreBuildDependencies.emplace(cc.Name);
  740. fastbuildTarget.PreBuildDependencies.emplace(cc.Name);
  741. this->GetGlobalGenerator()->AddTarget(std::move(cc));
  742. }
  743. for (auto& cc : GenerateCommands(FastbuildBuildStep::PRE_LINK).Nodes) {
  744. cc.PreBuildDependencies.emplace(fastbuildTarget.Name +
  745. FASTBUILD_DEPS_ARTIFACTS_ALIAS_POSTFIX);
  746. fastbuildTarget.PreLinkExecNodes.Nodes.emplace_back(std::move(cc));
  747. }
  748. for (auto& cc : GenerateCommands(FastbuildBuildStep::REST).Nodes) {
  749. fastbuildTarget.ExecNodes.PreBuildDependencies.emplace(cc.Name);
  750. this->GetGlobalGenerator()->AddTarget(std::move(cc));
  751. }
  752. for (auto& cc : GenerateCommands(FastbuildBuildStep::POST_BUILD).Nodes) {
  753. fastbuildTarget.PostBuildExecNodes.Alias.PreBuildDependencies.emplace(
  754. cc.Name);
  755. fastbuildTarget.PostBuildExecNodes.Nodes.emplace_back(std::move(cc));
  756. }
  757. GenerateObjects(fastbuildTarget);
  758. std::vector<std::string> objectDepends;
  759. AddObjectDependencies(fastbuildTarget, objectDepends);
  760. GenerateLink(fastbuildTarget, objectDepends);
  761. if (fastbuildTarget.LinkerNode.size() > 1) {
  762. if (!this->GeneratorTarget->IsApple()) {
  763. cmSystemTools::Error(
  764. "Can't handle more than 1 arch on non-Apple target");
  765. return;
  766. }
  767. AddLipoCommand(fastbuildTarget);
  768. }
  769. fastbuildTarget.CopyNodes = std::move(this->CopyNodes);
  770. // Generate symlink commands if real output name differs from "expected".
  771. for (auto& symlink : GetSymlinkExecs()) {
  772. fastbuildTarget.PostBuildExecNodes.Alias.PreBuildDependencies.emplace(
  773. symlink.Name);
  774. fastbuildTarget.PostBuildExecNodes.Nodes.emplace_back(std::move(symlink));
  775. }
  776. {
  777. auto appleTextStubCommand = GetAppleTextStubCommand();
  778. if (!appleTextStubCommand.Name.empty()) {
  779. fastbuildTarget.PostBuildExecNodes.Alias.PreBuildDependencies.emplace(
  780. appleTextStubCommand.Name);
  781. fastbuildTarget.PostBuildExecNodes.Nodes.emplace_back(
  782. std::move(appleTextStubCommand));
  783. }
  784. }
  785. AddPrebuildDeps(fastbuildTarget);
  786. fastbuildTarget.IsGlobal =
  787. GeneratorTarget->GetType() == cmStateEnums::GLOBAL_TARGET;
  788. fastbuildTarget.ExcludeFromAll =
  789. this->GetGlobalGenerator()->IsExcluded(GeneratorTarget);
  790. if (GeneratorTarget->GetPropertyAsBool("DONT_DISTRIBUTE")) {
  791. fastbuildTarget.AllowDistribution = false;
  792. }
  793. GenerateModuleDefinitionInfo(fastbuildTarget);
  794. // Needs to be called after we've added all PRE-LINK steps (like creation of
  795. // .def files on Windows).
  796. AddLinkerNodeDependnecies(fastbuildTarget);
  797. // Must be called after "GenerateObjects", since it also adds Prebuild deps
  798. // to it.
  799. // Also after "GenerateModuleDefinitionInfo", since uses PreLinkExecNodes.
  800. fastbuildTarget.GenerateAliases();
  801. if (!fastbuildTarget.ExecNodes.PreBuildDependencies.empty()) {
  802. fastbuildTarget.DependenciesAlias.PreBuildDependencies.emplace(
  803. fastbuildTarget.ExecNodes.Name);
  804. }
  805. fastbuildTarget.Hidden = false;
  806. fastbuildTarget.BasePath = this->GetMakefile()->GetCurrentSourceDirectory();
  807. this->GetGlobalGenerator()->AddIDEProject(fastbuildTarget, Config);
  808. AddStampExeIfApplicable(fastbuildTarget);
  809. // size 1 means that it's not a multi-arch lib (which can only be the case on
  810. // Darwin).
  811. if (fastbuildTarget.LinkerNode.size() == 1 &&
  812. fastbuildTarget.LinkerNode[0].Type ==
  813. FastbuildLinkerNode::STATIC_LIBRARY &&
  814. !fastbuildTarget.PostBuildExecNodes.Nodes.empty()) {
  815. ProcessPostBuildForStaticLib(fastbuildTarget);
  816. }
  817. AdditionalCleanFiles();
  818. if (!fastbuildTarget.DependenciesAlias.PreBuildDependencies.empty()) {
  819. for (FastbuildObjectListNode& objListNode :
  820. fastbuildTarget.ObjectListNodes) {
  821. objListNode.PreBuildDependencies.emplace(
  822. fastbuildTarget.DependenciesAlias.Name);
  823. }
  824. for (auto& linkerNode : fastbuildTarget.LinkerNode) {
  825. linkerNode.PreBuildDependencies.emplace(
  826. fastbuildTarget.DependenciesAlias.Name);
  827. }
  828. }
  829. this->GetGlobalGenerator()->AddTarget(std::move(fastbuildTarget));
  830. }
  831. void cmFastbuildNormalTargetGenerator::ProcessManifests(
  832. FastbuildLinkerNode& linkerNode) const
  833. {
  834. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  835. return;
  836. }
  837. auto manifests = this->GetManifestsAsFastbuildPath();
  838. if (manifests.empty()) {
  839. return;
  840. }
  841. // Manifests should always be in .Libraries2, so we re-link when needed.
  842. // Tested in RunCMake.BuildDepends
  843. for (auto const& manifest : manifests) {
  844. linkerNode.Libraries2.emplace_back(manifest);
  845. }
  846. if (this->Makefile->GetSafeDefinition("CMAKE_C_COMPILER_ID") != "MSVC") {
  847. return;
  848. }
  849. for (auto const& manifest : manifests) {
  850. linkerNode.LinkerOptions =
  851. cmStrCat("/MANIFESTINPUT:", manifest, ' ', linkerNode.LinkerOptions);
  852. }
  853. // /MANIFESTINPUT only works with /MANIFEST:EMBED
  854. linkerNode.LinkerOptions =
  855. cmStrCat("/MANIFEST:EMBED ", linkerNode.LinkerOptions);
  856. }
  857. void cmFastbuildNormalTargetGenerator::AddStampExeIfApplicable(
  858. FastbuildTarget& fastbuildTarget) const
  859. {
  860. LogMessage("AddStampExeIfApplicable(...)");
  861. if (fastbuildTarget.LinkerNode.empty() ||
  862. (fastbuildTarget.LinkerNode[0].Type != FastbuildLinkerNode::EXECUTABLE &&
  863. fastbuildTarget.LinkerNode[0].Type !=
  864. FastbuildLinkerNode::SHARED_LIBRARY)) {
  865. return;
  866. }
  867. // File which executes all POST_BUILD steps.
  868. // We use it in .LinkerStampExeArgs in order to run POST_BUILD steps after
  869. // the compilation.
  870. if (!fastbuildTarget.PostBuildExecNodes.Nodes.empty()) {
  871. std::string const AllPostBuildExecsScriptFile =
  872. cmStrCat(this->Makefile->GetHomeOutputDirectory(), "/CMakeFiles/",
  873. fastbuildTarget.Name,
  874. "-all-postbuild-commands" FASTBUILD_SCRIPT_FILE_EXTENSION);
  875. CollapseAllExecsIntoOneScriptfile(
  876. AllPostBuildExecsScriptFile, fastbuildTarget.PostBuildExecNodes.Nodes);
  877. auto& linkerNode = fastbuildTarget.LinkerNode.back();
  878. // On macOS, a target may have multiple linker nodes (e.g., for different
  879. // architectures). In that case, add the POST_BUILD step to only one node
  880. // to avoid running lipo multiple times.
  881. linkerNode.LinkerStampExe =
  882. cmGlobalFastbuildGenerator::GetExternalShellExecutable();
  883. linkerNode.LinkerStampExeArgs = FASTBUILD_SCRIPT_FILE_ARG;
  884. linkerNode.LinkerStampExeArgs +=
  885. cmGlobalFastbuildGenerator::QuoteIfHasSpaces(
  886. AllPostBuildExecsScriptFile);
  887. } else {
  888. LogMessage("No POST_BUILD steps for target: " + fastbuildTarget.Name);
  889. }
  890. }
  891. void cmFastbuildNormalTargetGenerator::ProcessPostBuildForStaticLib(
  892. FastbuildTarget& fastbuildTarget) const
  893. {
  894. // "Library" nodes do not have "LinkerStampExe" property, so we need to be
  895. // clever here: create an alias that will refer to the binary as well as to
  896. // all post-build steps. Also, make sure that post-build steps depend on the
  897. // binary itself.
  898. LogMessage("ProcessPostBuildForStaticLib(...)");
  899. FastbuildAliasNode alias;
  900. alias.Name = std::move(fastbuildTarget.LinkerNode[0].Name);
  901. for (FastbuildExecNode& postBuildExec :
  902. fastbuildTarget.PostBuildExecNodes.Nodes) {
  903. postBuildExec.PreBuildDependencies.emplace(
  904. fastbuildTarget.LinkerNode[0].LinkerOutput);
  905. alias.PreBuildDependencies.emplace(postBuildExec.Name);
  906. }
  907. fastbuildTarget.AliasNodes.emplace_back(std::move(alias));
  908. }
  909. void cmFastbuildNormalTargetGenerator::CollapseAllExecsIntoOneScriptfile(
  910. std::string const& scriptFileName,
  911. std::vector<FastbuildExecNode> const& execs) const
  912. {
  913. cmsys::ofstream scriptFile(scriptFileName.c_str());
  914. if (!scriptFile.is_open()) {
  915. cmSystemTools::Error("Failed to open: " + scriptFileName);
  916. return;
  917. }
  918. LogMessage("Writing collapsed Execs to " + scriptFileName);
  919. auto const shell = cmGlobalFastbuildGenerator::GetExternalShellExecutable();
  920. for (auto const& exec : execs) {
  921. if (exec.ScriptFile.empty()) {
  922. scriptFile << cmSystemTools::ConvertToOutputPath(exec.ExecExecutable)
  923. << " " << exec.ExecArguments << '\n';
  924. } else {
  925. #if defined(_WIN32)
  926. scriptFile << "call "
  927. << cmSystemTools::ConvertToWindowsOutputPath(exec.ScriptFile)
  928. << '\n';
  929. #else
  930. scriptFile << cmSystemTools::ConvertToOutputPath(shell) << " "
  931. << cmSystemTools::ConvertToOutputPath(exec.ScriptFile)
  932. << '\n';
  933. #endif
  934. }
  935. }
  936. }
  937. std::string cmFastbuildNormalTargetGenerator::ComputeCodeCheckOptions(
  938. cmSourceFile const& srcFile)
  939. {
  940. cmValue const srcSkipCodeCheckVal = srcFile.GetProperty("SKIP_LINTING");
  941. bool const skipCodeCheck = srcSkipCodeCheckVal.IsSet()
  942. ? srcSkipCodeCheckVal.IsOn()
  943. : this->GetGeneratorTarget()->GetPropertyAsBool("SKIP_LINTING");
  944. if (skipCodeCheck) {
  945. return {};
  946. }
  947. std::string compilerLauncher;
  948. std::string staticCheckRule = this->GenerateCodeCheckRules(
  949. srcFile, compilerLauncher, "", Config, nullptr);
  950. LogMessage(cmStrCat("CodeCheck: ", staticCheckRule));
  951. return staticCheckRule;
  952. }
  953. void cmFastbuildNormalTargetGenerator::ComputeCompilerAndOptions(
  954. std::string const& compilerOptions, std::string const& staticCheckOptions,
  955. std::string const& language, FastbuildObjectListNode& outObjectList)
  956. {
  957. auto& compilers = this->GetGlobalGenerator()->Compilers;
  958. auto const compilerIter =
  959. compilers.find(FASTBUILD_COMPILER_PREFIX + language);
  960. auto const launcherIter =
  961. compilers.find(FASTBUILD_LAUNCHER_PREFIX + language);
  962. if (!staticCheckOptions.empty()) {
  963. // If we want to run static checks - use CMake as a launcher.
  964. // Tested in "RunCMake.ClangTidy", "RunCMake.IncludeWhatYouUse",
  965. // "RunCMake.Cpplint", "RunCMake.Cppcheck", "RunCMake.MultiLint" tests.
  966. outObjectList.Compiler = "." FASTBUILD_LAUNCHER_PREFIX + CMAKE_LANGUAGE;
  967. outObjectList.CompilerOptions = staticCheckOptions;
  968. // Add compile command which will be passed to the static analyzer via
  969. // dash-dash.
  970. if (compilerIter != compilers.end()) {
  971. // Wrap in quotes to account for potential spaces in the path.
  972. outObjectList.CompilerOptions +=
  973. cmGlobalFastbuildGenerator::QuoteIfHasSpaces(
  974. compilerIter->second.Executable);
  975. outObjectList.CompilerOptions += compilerOptions;
  976. }
  977. } else if (launcherIter != compilers.end()) {
  978. // Tested in "RunCMake.CompilerLauncher" test.
  979. outObjectList.Compiler = "." + launcherIter->first;
  980. outObjectList.CompilerOptions = launcherIter->second.Args;
  981. auto vars = cmFastbuildNormalTargetGenerator::ComputeRuleVariables();
  982. vars.Language = language.c_str();
  983. std::string const targetSupportPath = this->ConvertToFastbuildPath(
  984. this->GetGeneratorTarget()->GetCMFSupportDirectory());
  985. vars.TargetSupportDir = targetSupportPath.c_str();
  986. RulePlaceholderExpander->ExpandRuleVariables(
  987. LocalCommonGenerator, outObjectList.CompilerOptions, vars);
  988. // Add compiler executable explicitly to the compile options.
  989. if (compilerIter != compilers.end()) {
  990. outObjectList.CompilerOptions += " ";
  991. // Wrap in quotes to account for potential spaces in the path.
  992. outObjectList.CompilerOptions +=
  993. cmGlobalFastbuildGenerator::QuoteIfHasSpaces(
  994. compilerIter->second.Executable);
  995. outObjectList.CompilerOptions += compilerOptions;
  996. }
  997. } else if (compilerIter != compilers.end()) {
  998. outObjectList.Compiler = "." + compilerIter->first;
  999. outObjectList.CompilerOptions = compilerOptions;
  1000. }
  1001. LogMessage(cmStrCat(".Compiler = ", outObjectList.Compiler));
  1002. LogMessage(cmStrCat(".CompilerOptions = ", outObjectList.CompilerOptions));
  1003. }
  1004. cmRulePlaceholderExpander::RuleVariables
  1005. cmFastbuildNormalTargetGenerator::ComputeRuleVariables() const
  1006. {
  1007. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  1008. compileObjectVars.CMTargetName = GeneratorTarget->GetName().c_str();
  1009. compileObjectVars.CMTargetType =
  1010. cmState::GetTargetTypeName(GeneratorTarget->GetType()).c_str();
  1011. compileObjectVars.CMTargetLabels =
  1012. this->GetGeneratorTarget()->GetTargetLabelsString().c_str();
  1013. compileObjectVars.Source = FASTBUILD_1_INPUT_PLACEHOLDER;
  1014. compileObjectVars.Object = FASTBUILD_2_INPUT_PLACEHOLDER;
  1015. compileObjectVars.ObjectDir =
  1016. FASTBUILD_DOLLAR_TAG "TargetOutputDir" FASTBUILD_DOLLAR_TAG;
  1017. compileObjectVars.ObjectFileDir = "";
  1018. compileObjectVars.Flags = "";
  1019. compileObjectVars.Includes = "";
  1020. compileObjectVars.Defines = "";
  1021. compileObjectVars.Includes = "";
  1022. compileObjectVars.TargetCompilePDB =
  1023. FASTBUILD_DOLLAR_TAG "CompilerPDB" FASTBUILD_DOLLAR_TAG;
  1024. compileObjectVars.Config = Config.c_str();
  1025. return compileObjectVars;
  1026. }
  1027. std::vector<std::string> cmFastbuildNormalTargetGenerator::GetSourceProperty(
  1028. cmSourceFile const& srcFile, std::string const& prop) const
  1029. {
  1030. std::vector<std::string> res;
  1031. if (cmValue val = srcFile.GetProperty(prop)) {
  1032. cmExpandList(*val, res);
  1033. return GetGlobalGenerator()->ConvertToFastbuildPath(res);
  1034. }
  1035. return res;
  1036. }
  1037. void cmFastbuildNormalTargetGenerator::AppendExtraResources(
  1038. std::set<std::string>& deps) const
  1039. {
  1040. // Generate Fastbuild's "Copy" commands to copy resources.
  1041. auto const generateCopyCommands =
  1042. [this](std::vector<cmSourceFile const*>& frameworkDeps) {
  1043. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  1044. frameworkDeps, this->MacOSXContentGenerator.get(), Config);
  1045. };
  1046. std::vector<cmSourceFile const*> headerSources;
  1047. this->GeneratorTarget->GetHeaderSources(headerSources, Config);
  1048. generateCopyCommands(headerSources);
  1049. std::vector<cmSourceFile const*> extraSources;
  1050. this->GeneratorTarget->GetExtraSources(extraSources, Config);
  1051. generateCopyCommands(extraSources);
  1052. std::vector<cmSourceFile const*> externalObjects;
  1053. this->GeneratorTarget->GetExternalObjects(externalObjects, Config);
  1054. generateCopyCommands(externalObjects);
  1055. for (FastbuildCopyNode const& node : this->CopyNodes) {
  1056. LogMessage("Adding resource: " + node.Name);
  1057. deps.emplace(node.Name);
  1058. }
  1059. }
  1060. std::string cmFastbuildNormalTargetGenerator::GetCompileOptions(
  1061. cmSourceFile const& srcFile, std::string const& arch)
  1062. {
  1063. std::string const language = srcFile.GetLanguage();
  1064. cmRulePlaceholderExpander::RuleVariables compileObjectVars =
  1065. ComputeRuleVariables();
  1066. std::string const compilerFlags = DetectCompilerFlags(srcFile, arch);
  1067. std::string const compilerDefines = ComputeDefines(srcFile);
  1068. compileObjectVars.Flags = compilerFlags.c_str();
  1069. compileObjectVars.Defines = compilerDefines.c_str();
  1070. compileObjectVars.Language = language.c_str();
  1071. std::string rule = CompileObjectCmakeRules.at(language);
  1072. RulePlaceholderExpander->ExpandRuleVariables(LocalCommonGenerator, rule,
  1073. compileObjectVars);
  1074. std::string compilerExecutable;
  1075. // Remove the compiler from .CompilerOptions, since it would be set as
  1076. // .Compiler in Fastbuild.
  1077. // See https://www.fastbuild.org/docs/functions/objectlist.html for a
  1078. // reference.
  1079. std::string options;
  1080. if (!cmSystemTools::SplitProgramFromArgs(rule, compilerExecutable,
  1081. options)) {
  1082. cmSystemTools::Error(cmStrCat("Failed to split compiler options: ", rule));
  1083. }
  1084. LogMessage("Expanded compile options = " + options);
  1085. LogMessage("Compiler executable = " + compilerExecutable);
  1086. return options;
  1087. }
  1088. std::vector<std::string> cmFastbuildNormalTargetGenerator::GetArches() const
  1089. {
  1090. auto arches = this->GetGeneratorTarget()->GetAppleArchs(Config, {});
  1091. // Don't add any arch-specific logic if arch is only one.
  1092. if (arches.empty() || arches.size() == 1) {
  1093. arches.clear();
  1094. arches.emplace_back();
  1095. }
  1096. return arches;
  1097. }
  1098. void cmFastbuildNormalTargetGenerator::GenerateObjects(FastbuildTarget& target)
  1099. {
  1100. this->GetGlobalGenerator()->AllFoldersToClean.insert(ObjectOutDir);
  1101. std::map<std::string, FastbuildObjectListNode> nodesPermutations;
  1102. cmCryptoHash hash(cmCryptoHash::AlgoSHA256);
  1103. std::vector<cmSourceFile const*> objectSources;
  1104. GeneratorTarget->GetObjectSources(objectSources, Config);
  1105. std::set<std::string> createdPCH;
  1106. // Directory level.
  1107. bool useUnity =
  1108. GeneratorTarget->GetLocalGenerator()->GetMakefile()->IsDefinitionSet(
  1109. CMAKE_UNITY_BUILD);
  1110. // Check if explicitly disabled for this target.
  1111. auto const targetProp = GeneratorTarget->GetProperty(UNITY_BUILD);
  1112. if (targetProp.IsSet() && targetProp.IsOff()) {
  1113. useUnity = false;
  1114. }
  1115. // List of sources isolated from the unity build if enabled.
  1116. std::set<std::string> isolatedFromUnity;
  1117. // Mapping from unity group (if any) to sources belonging to that group.
  1118. std::map<std::string, std::vector<std::string>> sourcesWithGroups;
  1119. for (cmSourceFile const* source : objectSources) {
  1120. cmSourceFile const& srcFile = *source;
  1121. std::string const pathToFile = srcFile.GetFullPath();
  1122. if (useUnity) {
  1123. // Check if the source should be added to "UnityInputIsolatedFiles".
  1124. if (srcFile.GetPropertyAsBool(SKIP_UNITY_BUILD_INCLUSION)) {
  1125. isolatedFromUnity.emplace(pathToFile);
  1126. }
  1127. std::string const perFileUnityGroup =
  1128. srcFile.GetSafeProperty(UNITY_GROUP);
  1129. if (!perFileUnityGroup.empty()) {
  1130. sourcesWithGroups[perFileUnityGroup].emplace_back(pathToFile);
  1131. }
  1132. }
  1133. this->GetGlobalGenerator()->AddFileToClean(cmStrCat(
  1134. ObjectOutDir, '/', this->GeneratorTarget->GetObjectName(source)));
  1135. // Do not generate separate node for PCH source file.
  1136. if (this->GeneratorTarget->GetPchSource(Config, srcFile.GetLanguage()) ==
  1137. pathToFile) {
  1138. continue;
  1139. }
  1140. std::string const language = srcFile.GetLanguage();
  1141. LogMessage(
  1142. cmStrCat("Source file: ", this->ConvertToFastbuildPath(pathToFile)));
  1143. LogMessage("Language: " + language);
  1144. std::string const staticCheckOptions = ComputeCodeCheckOptions(srcFile);
  1145. auto const isDisabled = [this](char const* prop) {
  1146. auto const propValue = this->GeneratorTarget->GetProperty(prop);
  1147. return propValue && propValue.IsOff();
  1148. };
  1149. bool const disableCaching = isDisabled("FASTBUILD_CACHING");
  1150. bool const disableDistribution = isDisabled("FASTBUILD_DISTRIBUTION");
  1151. for (auto const& arch : this->GetArches()) {
  1152. std::string const compileOptions = GetCompileOptions(srcFile, arch);
  1153. std::string objOutDirWithPossibleSubdir = ObjectOutDir;
  1154. // If object should be placed in some subdir in the output
  1155. // path. Tested in "SourceGroups" test.
  1156. auto const subdir = cmSystemTools::GetFilenamePath(
  1157. this->GeneratorTarget->GetObjectName(source));
  1158. if (!subdir.empty()) {
  1159. objOutDirWithPossibleSubdir += "/";
  1160. objOutDirWithPossibleSubdir += subdir;
  1161. }
  1162. std::string const objectListHash = hash.HashString(cmStrCat(
  1163. compileOptions, staticCheckOptions, objOutDirWithPossibleSubdir,
  1164. // If file does not need PCH - it must be in another ObjectList.
  1165. srcFile.GetProperty("SKIP_PRECOMPILE_HEADERS"),
  1166. srcFile.GetLanguage()));
  1167. LogMessage("ObjectList Hash: " + objectListHash);
  1168. FastbuildObjectListNode& objectListNode =
  1169. nodesPermutations[objectListHash];
  1170. // Absolute path needed in "RunCMake.SymlinkTrees" test.
  1171. objectListNode.CompilerInputFiles.push_back(pathToFile);
  1172. std::vector<std::string> const outputs =
  1173. GetSourceProperty(srcFile, "OBJECT_OUTPUTS");
  1174. objectListNode.ObjectOutputs.insert(outputs.begin(), outputs.end());
  1175. std::vector<std::string> const depends =
  1176. GetSourceProperty(srcFile, "OBJECT_DEPENDS");
  1177. objectListNode.ObjectDepends.insert(depends.begin(), depends.end());
  1178. // We have already computed properties that are computed below.
  1179. // (.CompilerOptions, .PCH*, etc.). Short circuit this iteration.
  1180. if (!objectListNode.CompilerOptions.empty()) {
  1181. continue;
  1182. }
  1183. if (disableCaching) {
  1184. objectListNode.AllowCaching = false;
  1185. }
  1186. if (disableDistribution) {
  1187. objectListNode.AllowDistribution = false;
  1188. }
  1189. objectListNode.CompilerOutputPath = objOutDirWithPossibleSubdir;
  1190. LogMessage(cmStrCat("Output path: ", objectListNode.CompilerOutputPath));
  1191. ComputeCompilerAndOptions(compileOptions, staticCheckOptions, language,
  1192. objectListNode);
  1193. ComputePCH(*source, objectListNode, createdPCH);
  1194. objectListNode.Name = cmStrCat(this->GetName(), '_', language, "_Objs");
  1195. // TODO: Ask cmake the output objects and group by extension instead
  1196. // of doing this
  1197. if (language == "RC") {
  1198. objectListNode.CompilerOutputExtension = ".res";
  1199. } else {
  1200. if (!arch.empty()) {
  1201. objectListNode.CompilerOutputExtension = cmStrCat('.', arch);
  1202. objectListNode.arch = arch;
  1203. }
  1204. objectListNode.CompilerOutputExtension +=
  1205. this->GetMakefile()->GetSafeDefinition(
  1206. cmStrCat("CMAKE_", language, "_OUTPUT_EXTENSION"));
  1207. }
  1208. }
  1209. }
  1210. int groupNameCount = 0;
  1211. for (auto& val : nodesPermutations) {
  1212. auto& objectListNode = val.second;
  1213. objectListNode.Name =
  1214. cmStrCat(objectListNode.Name, "_", std::to_string(++groupNameCount));
  1215. LogMessage(cmStrCat("ObjectList name: ", objectListNode.Name));
  1216. }
  1217. std::vector<FastbuildObjectListNode>& objects = target.ObjectListNodes;
  1218. objects.reserve(nodesPermutations.size());
  1219. for (auto& val : nodesPermutations) {
  1220. auto& node = val.second;
  1221. objects.emplace_back(std::move(node));
  1222. if (!objects.back().PCHInputFile.empty()) {
  1223. // Node that produces PCH should be the first one, since other nodes
  1224. // might reuse this PCH.
  1225. std::swap(*objects.begin(), objects.back());
  1226. }
  1227. }
  1228. if (useUnity) {
  1229. target.UnityNodes =
  1230. GenerateUnity(objects, isolatedFromUnity, sourcesWithGroups);
  1231. }
  1232. }
  1233. FastbuildUnityNode cmFastbuildNormalTargetGenerator::GetOneUnity(
  1234. std::set<std::string> const& isolatedFiles, std::vector<std::string>& files,
  1235. int unitySize) const
  1236. {
  1237. FastbuildUnityNode result;
  1238. for (auto iter = files.begin(); iter != files.end();) {
  1239. std::string pathToFile = std::move(*iter);
  1240. iter = files.erase(iter);
  1241. // This source must be isolated
  1242. if (isolatedFiles.find(pathToFile) != isolatedFiles.end()) {
  1243. result.UnityInputFiles.emplace_back(pathToFile);
  1244. result.UnityInputIsolatedFiles.emplace_back(std::move(pathToFile));
  1245. } else {
  1246. result.UnityInputFiles.emplace_back(std::move(pathToFile));
  1247. }
  1248. if (int(result.UnityInputFiles.size() -
  1249. result.UnityInputIsolatedFiles.size()) == unitySize) {
  1250. break;
  1251. }
  1252. }
  1253. return result;
  1254. }
  1255. int cmFastbuildNormalTargetGenerator::GetUnityBatchSize() const
  1256. {
  1257. int unitySize = 8;
  1258. try {
  1259. auto const perTargetSize =
  1260. GeneratorTarget->GetSafeProperty(UNITY_BUILD_BATCH_SIZE);
  1261. if (!perTargetSize.empty()) {
  1262. unitySize = std::stoi(perTargetSize);
  1263. }
  1264. // Per-directory level.
  1265. else {
  1266. unitySize = std::stoi(
  1267. GeneratorTarget->GetLocalGenerator()->GetMakefile()->GetDefinition(
  1268. CMAKE_UNITY_BUILD_BATCH_SIZE));
  1269. }
  1270. } catch (...) {
  1271. return unitySize;
  1272. }
  1273. return unitySize;
  1274. }
  1275. std::vector<FastbuildUnityNode>
  1276. cmFastbuildNormalTargetGenerator::GenerateUnity(
  1277. std::vector<FastbuildObjectListNode>& objects,
  1278. std::set<std::string> const& isolatedSources,
  1279. std::map<std::string, std::vector<std::string>> const& sourcesWithGroups)
  1280. {
  1281. int const unitySize = GetUnityBatchSize();
  1282. // Unity of size less than 2 doesn't make sense.
  1283. if (unitySize < 2) {
  1284. return {};
  1285. }
  1286. int unityNumber = 0;
  1287. int unityGroupNumber = 0;
  1288. std::vector<FastbuildUnityNode> result;
  1289. for (FastbuildObjectListNode& obj : objects) {
  1290. // Don't use unity for only 1 file.
  1291. if (obj.CompilerInputFiles.size() < 2) {
  1292. continue;
  1293. }
  1294. std::string const ext =
  1295. cmSystemTools::GetFilenameExtension(obj.CompilerInputFiles[0]);
  1296. // Process groups.
  1297. auto groupedNode = GenerateGroupedUnityNode(
  1298. obj.CompilerInputFiles, sourcesWithGroups, unityGroupNumber);
  1299. // We have at least 2 sources in the group.
  1300. if (groupedNode.UnityInputFiles.size() > 1) {
  1301. groupedNode.UnityOutputPath = obj.CompilerOutputPath;
  1302. obj.CompilerInputUnity.emplace_back(groupedNode.Name);
  1303. groupedNode.UnityOutputPattern = cmStrCat(groupedNode.Name, ext);
  1304. result.emplace_back(std::move(groupedNode));
  1305. }
  1306. // General unity batching of the remaining (non-grouped) sources.
  1307. while (!obj.CompilerInputFiles.empty()) {
  1308. FastbuildUnityNode node =
  1309. GetOneUnity(isolatedSources, obj.CompilerInputFiles, unitySize);
  1310. node.Name =
  1311. cmStrCat(this->GetName(), "_Unity_", std::to_string(++unityNumber));
  1312. node.UnityOutputPath = obj.CompilerOutputPath;
  1313. node.UnityOutputPattern = cmStrCat(node.Name, ext);
  1314. // Unity group of size 1 doesn't make sense - just isolate the source.
  1315. if (groupedNode.UnityInputFiles.size() == 1) {
  1316. node.UnityInputIsolatedFiles.emplace_back(
  1317. groupedNode.UnityInputFiles[0]);
  1318. node.UnityInputFiles.emplace_back(
  1319. std::move(groupedNode.UnityInputFiles[0]));
  1320. // Clear so we don't enter here on the next iteration.
  1321. groupedNode.UnityInputFiles.clear();
  1322. }
  1323. // We've got only 1 file left. No need to create a Unity node for it,
  1324. // just return it back to the ObjectList and exit.
  1325. if (node.UnityInputFiles.size() == 1) {
  1326. obj.CompilerInputFiles.emplace_back(
  1327. std::move(node.UnityInputFiles[0]));
  1328. break;
  1329. }
  1330. obj.CompilerInputUnity.emplace_back(node.Name);
  1331. result.emplace_back(std::move(node));
  1332. }
  1333. }
  1334. return result;
  1335. }
  1336. FastbuildUnityNode cmFastbuildNormalTargetGenerator::GenerateGroupedUnityNode(
  1337. std::vector<std::string>& inputFiles,
  1338. std::map<std::string, std::vector<std::string>> const& sourcesWithGroups,
  1339. int& groupId)
  1340. {
  1341. std::vector<FastbuildUnityNode> result;
  1342. for (auto const& item : sourcesWithGroups) {
  1343. auto const& group = item.first;
  1344. auto const& sources = item.second;
  1345. FastbuildUnityNode node;
  1346. // Check if any of the sources belong to this group.
  1347. for (auto const& source : sources) {
  1348. auto const iter =
  1349. std::find(inputFiles.begin(), inputFiles.end(), source);
  1350. if (iter == inputFiles.end()) {
  1351. continue;
  1352. }
  1353. node.Name = cmStrCat(this->GetName(), "_Unity_Group_", group, '_',
  1354. std::to_string(++groupId));
  1355. node.UnityInputFiles.emplace_back(source);
  1356. // Remove from the general batching.
  1357. inputFiles.erase(
  1358. std::remove(inputFiles.begin(), inputFiles.end(), source),
  1359. inputFiles.end());
  1360. }
  1361. if (!node.UnityInputFiles.empty()) {
  1362. // The unity group belongs to the ObjectLists that we're processing.
  1363. // We've grouped all the sources we could from the current ObjectList.
  1364. return node;
  1365. }
  1366. }
  1367. return {};
  1368. }
  1369. std::string cmFastbuildNormalTargetGenerator::ResolveIfAlias(
  1370. std::string const& targetName) const
  1371. {
  1372. LogMessage("targetName: " + targetName);
  1373. std::map<std::string, std::string> const aliases =
  1374. this->Makefile->GetAliasTargets();
  1375. auto const iter = aliases.find(targetName);
  1376. if (iter != aliases.end()) {
  1377. LogMessage("Non alias name: " + iter->second);
  1378. return iter->second;
  1379. }
  1380. return targetName;
  1381. }
  1382. void cmFastbuildNormalTargetGenerator::AppendExternalObject(
  1383. FastbuildLinkerNode& linkerNode, std::set<std::string>& linkedDeps) const
  1384. {
  1385. // Different aspects of this logic exercised in "ObjectLibrary" and
  1386. // "ExportImport" test. When making changes here - verify that both of those
  1387. // tests are still passing.
  1388. LogMessage("AppendExternalObject(...)");
  1389. std::vector<cmSourceFile const*> extObjects;
  1390. this->GeneratorTarget->GetExternalObjects(extObjects, Config);
  1391. for (cmSourceFile const* src : extObjects) {
  1392. std::string const pathToObj =
  1393. this->ConvertToFastbuildPath(src->GetFullPath());
  1394. LogMessage("EXT OBJ: " + pathToObj);
  1395. std::string const objLibName = ResolveIfAlias(src->GetObjectLibrary());
  1396. LogMessage("GetObjectLibrary: " + objLibName);
  1397. // Tested in "ExternalOBJ" test.
  1398. cmTarget const* target =
  1399. this->GlobalCommonGenerator->FindTarget(objLibName);
  1400. if (objLibName.empty()) {
  1401. linkerNode.LibrarianAdditionalInputs.emplace_back(pathToObj);
  1402. }
  1403. // We know how to generate this target and haven't added this dependency
  1404. // yet.
  1405. else if (target) {
  1406. if (!linkedDeps.emplace(objLibName + FASTBUILD_OBJECTS_ALIAS_POSTFIX)
  1407. .second) {
  1408. LogMessage("Object Target: " + objLibName +
  1409. FASTBUILD_OBJECTS_ALIAS_POSTFIX " already linked");
  1410. continue;
  1411. }
  1412. linkerNode.LibrarianAdditionalInputs.emplace_back(
  1413. objLibName + FASTBUILD_OBJECTS_ALIAS_POSTFIX);
  1414. } else if (linkedDeps.emplace(pathToObj).second) {
  1415. LogMessage("Adding obj dep : " + pathToObj);
  1416. linkerNode.LibrarianAdditionalInputs.emplace_back(pathToObj);
  1417. }
  1418. }
  1419. }
  1420. void cmFastbuildNormalTargetGenerator::AppendExeToLink(
  1421. FastbuildLinkerNode& linkerNode,
  1422. cmComputeLinkInformation::Item const& item) const
  1423. {
  1424. std::string const decorated =
  1425. item.GetFormattedItem(this->ConvertToFastbuildPath(item.Value.Value))
  1426. .Value;
  1427. LogMessage("Linking to executable : " + decorated);
  1428. // Tested in "InterfaceLinkLibrariesDirect" and "Plugin" test.
  1429. linkerNode.LinkerOptions +=
  1430. (" " + cmGlobalFastbuildGenerator::QuoteIfHasSpaces(decorated));
  1431. }
  1432. std::string cmFastbuildNormalTargetGenerator::GetImportedLoc(
  1433. cmComputeLinkInformation::Item const& item) const
  1434. {
  1435. // Link to import library when possible.
  1436. // Tested in "StagingPrefix" test on Windows/MSVC.
  1437. cmStateEnums::ArtifactType const artifact =
  1438. item.Target->HasImportLibrary(Config)
  1439. ? cmStateEnums::ImportLibraryArtifact
  1440. : cmStateEnums::RuntimeBinaryArtifact;
  1441. std::string importedLoc = this->ConvertToFastbuildPath(
  1442. item.Target->GetFullPath(Config, artifact, true));
  1443. LogMessage("ImportedGetLocation: " + importedLoc);
  1444. return importedLoc;
  1445. }
  1446. void cmFastbuildNormalTargetGenerator::AppendTargetDep(
  1447. FastbuildLinkerNode& linkerNode, std::set<std::string>& linkedObjects,
  1448. cmComputeLinkInformation::Item const& item) const
  1449. {
  1450. LogMessage("AppendTargetDep(...)");
  1451. cmStateEnums::TargetType const depType = item.Target->GetType();
  1452. LogMessage("Link dep type: " + std::to_string(depType));
  1453. LogMessage("Target name: " + item.Target->GetName());
  1454. auto const resolvedTargetName = ResolveIfAlias(item.Target->GetName());
  1455. LogMessage("Resolved: " + resolvedTargetName);
  1456. if (depType == cmStateEnums::INTERFACE_LIBRARY) {
  1457. return;
  1458. }
  1459. std::string const feature = item.GetFeatureName();
  1460. if (item.Target->IsImported()) {
  1461. if (feature == "FRAMEWORK") {
  1462. // Use just framework's name. The exact path where to look for the
  1463. // framework will be provided from "frameworkPath" in
  1464. // "cmFastbuildNormalTargetGenerator::DetectBaseLinkerCommand(...)".
  1465. // Tested in "RunCMake.Framework - ImportedFrameworkConsumption".
  1466. std::string const decorated =
  1467. item.GetFormattedItem(item.Value.Value).Value;
  1468. LogMessage("Adding framework dep <" + decorated + "> to command line");
  1469. linkerNode.LinkerOptions += (" " + decorated);
  1470. return;
  1471. }
  1472. if (depType == cmStateEnums::UNKNOWN_LIBRARY) {
  1473. LogMessage("Unknown library -- adding to LibrarianAdditionalInputs or "
  1474. "Libraries2");
  1475. if (UsingCommandLine) {
  1476. AppendCommandLineDep(linkerNode, item);
  1477. } else {
  1478. AppendLinkDep(linkerNode, GetImportedLoc(item));
  1479. }
  1480. return;
  1481. }
  1482. // Tested in "ExportImport" test.
  1483. if (depType == cmStateEnums::EXECUTABLE) {
  1484. AppendExeToLink(linkerNode, item);
  1485. return;
  1486. }
  1487. // Skip exported objects.
  1488. // Tested in "ExportImport" test.
  1489. if (depType == cmStateEnums::OBJECT_LIBRARY) {
  1490. LogMessage("target : " + item.Target->GetName() +
  1491. " already linked... Skipping");
  1492. return;
  1493. }
  1494. // Tested in "ExportImport" test.
  1495. cmList const list{ GetImportedLoc(item) };
  1496. for (std::string const& linkDep : list) {
  1497. AppendLinkDep(linkerNode, linkDep);
  1498. }
  1499. } else {
  1500. if (depType == cmStateEnums::SHARED_LIBRARY &&
  1501. this->GeneratorTarget->GetPropertyAsBool("LINK_DEPENDS_NO_SHARED")) {
  1502. // It moves the dep outside of FASTBuild control, so the binary won't
  1503. // be re-built if the shared lib has changed.
  1504. // Tested in "BuildDepends" test.
  1505. LogMessage("LINK_DEPENDS_NO_SHARED is set on the target, adding dep" +
  1506. item.Value.Value + " as is");
  1507. linkerNode.LinkerOptions +=
  1508. (" " + cmGlobalFastbuildGenerator::QuoteIfHasSpaces(item.Value.Value));
  1509. return;
  1510. }
  1511. // Just add path to binary artifact to command line (except for OBJECT
  1512. // libraries which we will link directly).
  1513. if (UsingCommandLine && depType != cmStateEnums::OBJECT_LIBRARY) {
  1514. AppendCommandLineDep(linkerNode, item);
  1515. return;
  1516. }
  1517. // This dep has a special way of linking to it (e.g.
  1518. // "CMAKE_LINK_LIBRARY_USING_<FEATURE>").
  1519. bool const isFeature = !feature.empty() && feature != "DEFAULT";
  1520. if (isFeature) {
  1521. std::string const decorated =
  1522. item.GetFormattedItem(this->ConvertToFastbuildPath(item.Value.Value))
  1523. .Value;
  1524. LogMessage("Prepending with feature: " + decorated);
  1525. linkerNode.LinkerOptions += (" " + decorated);
  1526. }
  1527. std::string dep = resolvedTargetName +
  1528. (depType == cmStateEnums::OBJECT_LIBRARY
  1529. ? FASTBUILD_OBJECTS_ALIAS_POSTFIX
  1530. : FASTBUILD_LINK_ARTIFACTS_ALIAS_POSTFIX);
  1531. if (!linkerNode.Arch.empty()) {
  1532. dep += cmStrCat('-', linkerNode.Arch);
  1533. }
  1534. // If we have a special way of linking the dep, we can't have it in
  1535. // ".Libraries" (since there might be multiple such deps, but
  1536. // FASTBuild expands ".Libraries" as a continuous array, so we can't
  1537. // inject any properties in between). Tested in
  1538. // "RunCMake.target_link_libraries-LINK_LIBRARY" test.
  1539. if (isFeature) {
  1540. LogMessage("AppendTargetDep: " + dep + " as prebuild");
  1541. linkerNode.PreBuildDependencies.emplace(dep);
  1542. return;
  1543. }
  1544. if (depType != cmStateEnums::OBJECT_LIBRARY ||
  1545. linkedObjects.emplace(dep).second) {
  1546. AppendLinkDep(linkerNode, dep);
  1547. }
  1548. AppendTransitivelyLinkedObjects(*item.Target, linkedObjects);
  1549. }
  1550. }
  1551. void cmFastbuildNormalTargetGenerator::AppendPrebuildDeps(
  1552. FastbuildLinkerNode& linkerNode,
  1553. cmComputeLinkInformation::Item const& item) const
  1554. {
  1555. if (!item.Target->IsImported()) {
  1556. return;
  1557. }
  1558. // In "RunCMake.FileAPI" imported object library "imported_object_lib" is
  1559. // added w/o import location...
  1560. if (item.Target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1561. return;
  1562. }
  1563. cmList const list{ GetImportedLoc(item) };
  1564. for (std::string const& linkDep : list) {
  1565. // In case we know how to generate this file (needed for proper
  1566. // sorting by deps). Tested in "RunCMake.target_link_libraries-ALIAS"
  1567. // test.
  1568. auto fastbuildTarget =
  1569. this->GetGlobalGenerator()->GetTargetByOutputName(linkDep);
  1570. std::string fastbuildTargetName;
  1571. if (fastbuildTarget) {
  1572. fastbuildTargetName = std::move(fastbuildTarget->Name);
  1573. }
  1574. if (!fastbuildTargetName.empty()) {
  1575. LogMessage("Adding dep to " + fastbuildTargetName);
  1576. linkerNode.PreBuildDependencies.insert(std::move(fastbuildTargetName));
  1577. } else {
  1578. if (!cmIsNOTFOUND(linkDep)) {
  1579. LogMessage("Adding dep " + linkDep + " for sorting");
  1580. linkerNode.PreBuildDependencies.insert(linkDep);
  1581. }
  1582. }
  1583. }
  1584. }
  1585. void cmFastbuildNormalTargetGenerator::AppendTransitivelyLinkedObjects(
  1586. cmGeneratorTarget const& target, std::set<std::string>& linkedObjects) const
  1587. {
  1588. std::vector<std::string> objs;
  1589. // Consider that all those object are now linked as well.
  1590. // Tested in "ExportImport" test.
  1591. target.GetTargetObjectNames(Config, objs);
  1592. for (std::string const& obj : objs) {
  1593. std::string const pathToObj = this->ConvertToFastbuildPath(
  1594. cmStrCat(target.GetObjectDirectory(Config), '/', obj));
  1595. linkedObjects.insert(pathToObj);
  1596. }
  1597. // Object libs should not be propagated transitively. It's especially
  1598. // important for LinkObjRHSObject2 test where the absence of the propagation
  1599. // is tested.
  1600. for (auto const& linkedTarget :
  1601. target.Target->GetLinkImplementationEntries()) {
  1602. auto objAlias = linkedTarget.Value + FASTBUILD_OBJECTS_ALIAS_POSTFIX;
  1603. LogMessage("Object target is linked transitively " + objAlias);
  1604. linkedObjects.emplace(std::move(objAlias));
  1605. }
  1606. }
  1607. void cmFastbuildNormalTargetGenerator::AppendCommandLineDep(
  1608. FastbuildLinkerNode& linkerNode,
  1609. cmComputeLinkInformation::Item const& item) const
  1610. {
  1611. LogMessage("AppendCommandLineDep(...)");
  1612. // Tested in:
  1613. // "LinkDirectory" (TargetType::EXECUTABLE),
  1614. // "ObjC.simple-build-test" (TargetType::SHARED_LIBRARY),
  1615. // "XCTest" (TargetType::MODULE_LIBRARY) tests.
  1616. std::string formatted;
  1617. if (item.Target && item.Target->IsImported()) {
  1618. formatted = GetImportedLoc(item);
  1619. } else {
  1620. formatted = item.GetFormattedItem(item.Value.Value).Value;
  1621. }
  1622. formatted = this->ConvertToFastbuildPath(formatted);
  1623. LogMessage("Unknown link dep: " + formatted + ", adding to command line");
  1624. // Only add real artifacts to .Libraries2, otherwise Fastbuild will always
  1625. // consider the target out-of-date (since its input doesn't exist).
  1626. if (item.IsPath == cmComputeLinkInformation::ItemIsPath::Yes &&
  1627. item.GetFeatureName() == "DEFAULT") {
  1628. linkerNode.LinkerOptions +=
  1629. (" " + cmGlobalFastbuildGenerator::QuoteIfHasSpaces(formatted));
  1630. AppendToLibraries2IfApplicable(linkerNode, std::move(formatted));
  1631. } else {
  1632. // It's some link option, not a path.
  1633. linkerNode.LinkerOptions += (" " + formatted);
  1634. }
  1635. }
  1636. void cmFastbuildNormalTargetGenerator::AppendToLibraries2IfApplicable(
  1637. FastbuildLinkerNode& linkerNode, std::string dep) const
  1638. {
  1639. // Strings like "-framework Cocoa" in .Libraries2 node will always make the
  1640. // target out-of-date (since it never exists).
  1641. if (this->GeneratorTarget->IsApple() &&
  1642. cmSystemTools::StringStartsWith(dep, "-framework")) {
  1643. LogMessage("Not adding framework: " + dep + " to .Libraries2");
  1644. return;
  1645. }
  1646. auto const target = this->GetGlobalGenerator()->GetTargetByOutputName(dep);
  1647. // Fastbuild doesn't support executables in .Libraries2, though we can use
  1648. // Executables via "-bundle_loader" on Apple.
  1649. if (this->GeneratorTarget->IsApple() && target &&
  1650. !target->LinkerNode.empty() &&
  1651. target->LinkerNode[0].Type == FastbuildLinkerNode::EXECUTABLE) {
  1652. LogMessage("Not adding DLL/Executable(" + linkerNode.Name +
  1653. " to .Libraries2");
  1654. return;
  1655. }
  1656. // Additing to .Libraries2 for tracking.
  1657. LogMessage("Adding " + dep + " .Libraries2");
  1658. linkerNode.Libraries2.emplace_back(std::move(dep));
  1659. }
  1660. void cmFastbuildNormalTargetGenerator::AppendLINK_DEPENDS(
  1661. FastbuildLinkerNode& linkerNode) const
  1662. {
  1663. // LINK_DEPENDS and such.
  1664. // Tested in "BuildDepends" test.
  1665. for (std::string const& lang : Languages) {
  1666. for (BT<std::string> const& dep :
  1667. this->GeneratorTarget->GetLinkDepends(Config, lang)) {
  1668. // We can't add "LINK_DEPENDS" to .PreBuildDependencies, since FASTBuild
  1669. // only forces such targets to be built and doesn't force re-linking if
  1670. // they've changed.
  1671. linkerNode.Libraries2.emplace_back(
  1672. this->ConvertToFastbuildPath(dep.Value));
  1673. }
  1674. }
  1675. }
  1676. void cmFastbuildNormalTargetGenerator::AppendLinkDep(
  1677. FastbuildLinkerNode& linkerNode, std::string dep) const
  1678. {
  1679. LogMessage("AppendLinkDep: " + dep +
  1680. " to .LibrarianAdditionalInputs/.Libraries");
  1681. linkerNode.LibrarianAdditionalInputs.emplace_back(std::move(dep));
  1682. }
  1683. void cmFastbuildNormalTargetGenerator::AppendDirectObjectLibs(
  1684. FastbuildLinkerNode& linkerNode, std::set<std::string>& linkedObjects)
  1685. {
  1686. auto const srcs = this->GeneratorTarget->GetSourceFiles(Config);
  1687. for (auto const& entry : srcs) {
  1688. auto const objLib = entry.Value->GetObjectLibrary();
  1689. auto const objPath = entry.Value->GetFullPath();
  1690. LogMessage("Source obj entry: " + objPath);
  1691. if (!objLib.empty()) {
  1692. auto* const objTarget =
  1693. this->LocalGenerator->FindGeneratorTargetToUse(objLib);
  1694. if (objTarget) {
  1695. LogMessage("Imported: " + std::to_string(objTarget->IsImported()));
  1696. std::string fastbuildTarget;
  1697. // If target is imported - we don't have it in our build file, so can't
  1698. // refer to it by name. Use file path to the object then.
  1699. // Tested in "ExportImport" test.
  1700. if (objTarget->IsImported()) {
  1701. fastbuildTarget = entry.Value->GetFullPath();
  1702. } else {
  1703. // Mark all target objects as linked.
  1704. linkedObjects.emplace(this->ConvertToFastbuildPath(objPath));
  1705. fastbuildTarget =
  1706. objTarget->GetName() + FASTBUILD_OBJECTS_ALIAS_POSTFIX;
  1707. }
  1708. if (linkedObjects.emplace(fastbuildTarget).second) {
  1709. LogMessage("Adding object target: " + fastbuildTarget);
  1710. linkerNode.LibrarianAdditionalInputs.emplace_back(
  1711. std::move(fastbuildTarget));
  1712. }
  1713. }
  1714. }
  1715. }
  1716. }
  1717. void cmFastbuildNormalTargetGenerator::AppendLinkDeps(
  1718. std::set<FastbuildTargetDep>& preBuildDeps, FastbuildLinkerNode& linkerNode)
  1719. {
  1720. std::set<std::string> linkedObjects;
  1721. cmComputeLinkInformation const* linkInfo =
  1722. this->GeneratorTarget->GetLinkInformation(Config);
  1723. if (!linkInfo) {
  1724. return;
  1725. }
  1726. UsingCommandLine = false;
  1727. AppendLINK_DEPENDS(linkerNode);
  1728. // Object libs that are linked directly to target (e.g.
  1729. // add_executable(test_exe archiveObjs)
  1730. AppendDirectObjectLibs(linkerNode, linkedObjects);
  1731. // target_link_libraries.
  1732. cmComputeLinkInformation::ItemVector const items = linkInfo->GetItems();
  1733. LogMessage(cmStrCat("Link items size: ", items.size()));
  1734. for (cmComputeLinkInformation::Item const& item : items) {
  1735. std::string const feature = item.GetFeatureName();
  1736. LogMessage("GetFeatureName: " + feature);
  1737. if (!feature.empty()) {
  1738. LogMessage("GetFormattedItem: " +
  1739. item.GetFormattedItem(item.Value.Value).Value);
  1740. }
  1741. // We're linked to `$<TARGET_OBJECTS>`.
  1742. // Static libs transitively propagate such deps, see:
  1743. // https://cmake.org/cmake/help/latest/command/target_link_libraries.html#linking-object-libraries-via-target-objects
  1744. if (item.ObjectSource &&
  1745. linkerNode.Type != FastbuildLinkerNode::STATIC_LIBRARY) {
  1746. // Tested in "ObjectLibrary" test.
  1747. auto libName = item.ObjectSource->GetObjectLibrary();
  1748. std::string dep = libName + FASTBUILD_OBJECTS_ALIAS_POSTFIX;
  1749. if (linkedObjects.emplace(dep).second) {
  1750. FastbuildTargetDep targetDep{ std::move(libName) };
  1751. targetDep.Type = FastbuildTargetDepType::ORDER_ONLY;
  1752. preBuildDeps.emplace(std::move(targetDep));
  1753. linkerNode.LibrarianAdditionalInputs.emplace_back(std::move(dep));
  1754. }
  1755. } else if (linkerNode.Type == FastbuildLinkerNode::STATIC_LIBRARY) {
  1756. LogMessage("Skipping linking to STATIC_LIBRARY (" + linkerNode.Name +
  1757. ")");
  1758. continue;
  1759. }
  1760. // We're linked to exact target.
  1761. else if (item.Target) {
  1762. AppendTargetDep(linkerNode, linkedObjects, item);
  1763. AppendPrebuildDeps(linkerNode, item);
  1764. } else {
  1765. AppendCommandLineDep(linkerNode, item);
  1766. UsingCommandLine = true;
  1767. }
  1768. }
  1769. AppendExternalObject(linkerNode, linkedObjects);
  1770. }
  1771. void cmFastbuildNormalTargetGenerator::AddLipoCommand(FastbuildTarget& target)
  1772. {
  1773. static auto const lipo = cmSystemTools::FindProgram("lipo");
  1774. LogMessage("found lipo at " + lipo);
  1775. FastbuildExecNode exec;
  1776. exec.ExecExecutable = lipo;
  1777. exec.ExecOutput = target.RealOutput;
  1778. if (exec.ExecOutput != target.Name) {
  1779. exec.Name = target.Name;
  1780. }
  1781. for (auto const& ArchSpecificTarget : target.LinkerNode) {
  1782. exec.ExecInput.emplace_back(ArchSpecificTarget.LinkerOutput);
  1783. }
  1784. exec.ExecArguments +=
  1785. "-create -output " + target.RealOutput + " " + cmJoin(exec.ExecInput, " ");
  1786. target.PostBuildExecNodes.Alias.PreBuildDependencies.emplace(
  1787. exec.ExecOutput);
  1788. target.PostBuildExecNodes.Nodes.emplace_back(std::move(exec));
  1789. }
  1790. void cmFastbuildNormalTargetGenerator::GenerateLink(
  1791. FastbuildTarget& target, std::vector<std::string> const& objectDepends)
  1792. {
  1793. std::string const targetName = this->GetTargetName();
  1794. cmGeneratorTarget::Names const targetNames = DetectOutput();
  1795. LogMessage("targetNames.Real: " + targetNames.Real);
  1796. LogMessage("targetNames.ImportOutput: " + targetNames.ImportOutput);
  1797. LogMessage("targetNames.SharedObject: " + targetNames.SharedObject);
  1798. LogMessage("targetNames.Base: " + targetNames.Base);
  1799. std::vector<std::string> allNodes;
  1800. auto const arches = this->GetArches();
  1801. for (std::size_t i = 0; i < arches.size(); ++i) {
  1802. auto const& arch = arches[i];
  1803. FastbuildLinkerNode linkerNode;
  1804. ProcessManifests(linkerNode);
  1805. // Objects built by the current target.
  1806. for (auto const& objectList : target.ObjectListNodes) {
  1807. if (objectList.arch.empty() || objectList.arch == arch) {
  1808. linkerNode.LibrarianAdditionalInputs.push_back(objectList.Name);
  1809. }
  1810. }
  1811. // Detection of the link command as follows:
  1812. auto const type = this->GeneratorTarget->GetType();
  1813. switch (type) {
  1814. case cmStateEnums::EXECUTABLE: {
  1815. LogMessage("Generating EXECUTABLE");
  1816. linkerNode.Type = FastbuildLinkerNode::EXECUTABLE;
  1817. break;
  1818. }
  1819. case cmStateEnums::MODULE_LIBRARY: {
  1820. LogMessage("Generating MODULE_LIBRARY");
  1821. linkerNode.Type = FastbuildLinkerNode::SHARED_LIBRARY;
  1822. break;
  1823. }
  1824. case cmStateEnums::SHARED_LIBRARY: {
  1825. LogMessage("Generating SHARED_LIBRARY");
  1826. linkerNode.Type = FastbuildLinkerNode::SHARED_LIBRARY;
  1827. break;
  1828. }
  1829. case cmStateEnums::STATIC_LIBRARY: {
  1830. LogMessage("Generating STATIC_LIBRARY");
  1831. linkerNode.Type = FastbuildLinkerNode::STATIC_LIBRARY;
  1832. break;
  1833. }
  1834. case cmStateEnums::OBJECT_LIBRARY: {
  1835. LogMessage("Generating OBJECT_LIBRARY");
  1836. return;
  1837. }
  1838. default: {
  1839. LogMessage("Skipping GenerateLink");
  1840. return;
  1841. }
  1842. }
  1843. std::string const targetOutput =
  1844. ConvertToFastbuildPath(GeneratorTarget->GetFullPath(Config));
  1845. std::string targetOutputReal = ConvertToFastbuildPath(
  1846. GeneratorTarget->GetFullPath(Config, cmStateEnums::RuntimeBinaryArtifact,
  1847. /*realname=*/true));
  1848. LogMessage("targetOutput: " + targetOutput);
  1849. LogMessage("targetOutputReal: " + targetOutputReal);
  1850. std::string const output =
  1851. cmSystemTools::GetFilenameName(targetNames.Output);
  1852. std::string const outputReal =
  1853. cmSystemTools::GetFilenameName(targetNames.Real);
  1854. // Generate "Copy" nodes for copying Framework / Bundle resources.
  1855. AppendExtraResources(linkerNode.PreBuildDependencies);
  1856. if (type == cmStateEnums::EXECUTABLE ||
  1857. type == cmStateEnums::SHARED_LIBRARY) {
  1858. // Tested in "RunCMake.BuildDepends" test (we need to rebuild when
  1859. // manifest changes).
  1860. std::copy(objectDepends.begin(), objectDepends.end(),
  1861. std::back_inserter(linkerNode.Libraries2));
  1862. }
  1863. if (GeneratorTarget->IsAppBundleOnApple()) {
  1864. // Create the app bundle
  1865. std::string outpath = GeneratorTarget->GetDirectory(Config);
  1866. this->OSXBundleGenerator->CreateAppBundle(targetNames.Output, outpath,
  1867. Config);
  1868. targetOutputReal = outpath;
  1869. targetOutputReal += "/";
  1870. targetOutputReal += outputReal;
  1871. targetOutputReal = this->ConvertToFastbuildPath(targetOutputReal);
  1872. } else if (GeneratorTarget->IsFrameworkOnApple()) {
  1873. // Create the library framework.
  1874. this->OSXBundleGenerator->CreateFramework(
  1875. targetNames.Output, GeneratorTarget->GetDirectory(Config), Config);
  1876. } else if (GeneratorTarget->IsCFBundleOnApple()) {
  1877. // Create the core foundation bundle.
  1878. this->OSXBundleGenerator->CreateCFBundle(
  1879. targetNames.Output, GeneratorTarget->GetDirectory(Config), Config);
  1880. }
  1881. std::string linkCmd;
  1882. if (!DetectBaseLinkerCommand(linkCmd, arch, targetNames)) {
  1883. LogMessage("No linker command detected");
  1884. return;
  1885. }
  1886. std::string executable;
  1887. std::string linkerOptions;
  1888. std::string linkerType = "auto";
  1889. GetLinkerExecutableAndArgs(linkCmd, executable, linkerOptions);
  1890. linkerNode.Compiler = ".Compiler_dummy";
  1891. linkerNode.CompilerOptions = " ";
  1892. linkerNode.Name = targetName;
  1893. linkerNode.LinkerOutput = targetOutputReal;
  1894. this->GetGlobalGenerator()->AddFileToClean(linkerNode.LinkerOutput);
  1895. target.RealOutput = targetOutputReal;
  1896. if (!arch.empty()) {
  1897. linkerNode.Name += cmStrCat('-', arch);
  1898. linkerNode.LinkerOutput += cmStrCat('.', arch);
  1899. linkerNode.Arch = arch;
  1900. }
  1901. linkerNode.Linker = executable;
  1902. linkerNode.LinkerType = linkerType;
  1903. linkerNode.LinkerOptions += linkerOptions;
  1904. AppendLinkDeps(target.PreBuildDependencies, linkerNode);
  1905. ApplyLWYUToLinkerCommand(linkerNode);
  1906. // On macOS, only the last LinkerNode performs lipo in POST_BUILD.
  1907. // Make it depend on all previous nodes to ensure correct execution order.
  1908. if (i == arches.size() - 1) {
  1909. for (auto& prevNode : allNodes) {
  1910. linkerNode.PreBuildDependencies.emplace(std::move(prevNode));
  1911. }
  1912. } else {
  1913. allNodes.emplace_back(linkerNode.Name);
  1914. }
  1915. if (!target.ObjectListNodes.empty()) {
  1916. // Just reuse any of compiler options mainly for the correct IDE project
  1917. // generation.
  1918. linkerNode.CompilerOptions = target.ObjectListNodes[0].CompilerOptions;
  1919. }
  1920. target.LinkerNode.emplace_back(std::move(linkerNode));
  1921. }
  1922. }
  1923. std::vector<FastbuildExecNode>
  1924. cmFastbuildNormalTargetGenerator::GetSymlinkExecs() const
  1925. {
  1926. std::vector<FastbuildExecNode> res;
  1927. cmGeneratorTarget::Names const targetNames = DetectOutput();
  1928. LogMessage("targetNames.Real: " + targetNames.Real);
  1929. LogMessage("targetNames.ImportOutput: " + targetNames.ImportOutput);
  1930. LogMessage("targetNames.SharedObject: " + targetNames.SharedObject);
  1931. LogMessage("targetNames.Base: " + targetNames.Base);
  1932. std::string const targetOutput =
  1933. ConvertToFastbuildPath(GeneratorTarget->GetFullPath(Config));
  1934. std::string const targetOutputReal = ConvertToFastbuildPath(
  1935. GeneratorTarget->GetFullPath(Config, cmStateEnums::RuntimeBinaryArtifact,
  1936. /*realname=*/true));
  1937. LogMessage("targetOutput: " + targetOutput);
  1938. LogMessage("targetOutputReal: " + targetOutputReal);
  1939. if (targetOutput != targetOutputReal &&
  1940. !GeneratorTarget->IsFrameworkOnApple()) {
  1941. auto const generateSymlinkCommand = [&](std::string const& from,
  1942. std::string const& to) {
  1943. if (from.empty() || to.empty() || from == to) {
  1944. return;
  1945. }
  1946. LogMessage("Symlinking " + from + " -> " + to);
  1947. FastbuildExecNode postBuildExecNode;
  1948. postBuildExecNode.Name = "cmake_symlink_" + to;
  1949. postBuildExecNode.ExecOutput =
  1950. cmJoin({ GeneratorTarget->GetDirectory(Config), to }, "/");
  1951. postBuildExecNode.ExecExecutable = cmSystemTools::GetCMakeCommand();
  1952. postBuildExecNode.ExecArguments =
  1953. "-E cmake_symlink_executable " +
  1954. cmGlobalFastbuildGenerator::QuoteIfHasSpaces(from) + " " +
  1955. cmGlobalFastbuildGenerator::QuoteIfHasSpaces(
  1956. this->ConvertToFastbuildPath(postBuildExecNode.ExecOutput));
  1957. res.emplace_back(std::move(postBuildExecNode));
  1958. };
  1959. generateSymlinkCommand(targetNames.Real, targetNames.Output);
  1960. generateSymlinkCommand(targetNames.Real, targetNames.SharedObject);
  1961. generateSymlinkCommand(targetNames.ImportReal, targetNames.ImportOutput);
  1962. }
  1963. return res;
  1964. }