cmMakefileTargetGenerator.cxx 84 KB

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