cmMakefileTargetGenerator.cxx 91 KB

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