cmMakefileTargetGenerator.cxx 93 KB

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