cmMakefileTargetGenerator.cxx 90 KB

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