cmComputeLinkDepends.cxx 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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 "cmComputeLinkDepends.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cstddef>
  7. #include <cstdio>
  8. #include <iterator>
  9. #include <sstream>
  10. #include <type_traits>
  11. #include <unordered_map>
  12. #include <utility>
  13. #include <cm/memory>
  14. #include <cm/string_view>
  15. #include <cmext/string_view>
  16. #include "cmComputeComponentGraph.h"
  17. #include "cmGeneratorExpression.h"
  18. #include "cmGeneratorExpressionDAGChecker.h"
  19. #include "cmGeneratorTarget.h"
  20. #include "cmGlobalGenerator.h"
  21. #include "cmList.h"
  22. #include "cmListFileCache.h"
  23. #include "cmLocalGenerator.h"
  24. #include "cmMakefile.h"
  25. #include "cmMessageType.h"
  26. #include "cmRange.h"
  27. #include "cmStateTypes.h"
  28. #include "cmStringAlgorithms.h"
  29. #include "cmTarget.h"
  30. #include "cmValue.h"
  31. #include "cmake.h"
  32. /*
  33. This file computes an ordered list of link items to use when linking a
  34. single target in one configuration. Each link item is identified by
  35. the string naming it. A graph of dependencies is created in which
  36. each node corresponds to one item and directed edges lead from nodes to
  37. those which must *follow* them on the link line. For example, the
  38. graph
  39. A -> B -> C
  40. will lead to the link line order
  41. A B C
  42. The set of items placed in the graph is formed with a breadth-first
  43. search of the link dependencies starting from the main target.
  44. There are two types of items: those with known direct dependencies and
  45. those without known dependencies. We will call the two types "known
  46. items" and "unknown items", respectively. Known items are those whose
  47. names correspond to targets (built or imported) and those for which an
  48. old-style <item>_LIB_DEPENDS variable is defined. All other items are
  49. unknown and we must infer dependencies for them. For items that look
  50. like flags (beginning with '-') we trivially infer no dependencies,
  51. and do not include them in the dependencies of other items.
  52. Known items have dependency lists ordered based on how the user
  53. specified them. We can use this order to infer potential dependencies
  54. of unknown items. For example, if link items A and B are unknown and
  55. items X and Y are known, then we might have the following dependency
  56. lists:
  57. X: Y A B
  58. Y: A B
  59. The explicitly known dependencies form graph edges
  60. X -> Y , X -> A , X -> B , Y -> A , Y -> B
  61. We can also infer the edge
  62. A -> B
  63. because *every* time A appears B is seen on its right. We do not know
  64. whether A really needs symbols from B to link, but it *might* so we
  65. must preserve their order. This is the case also for the following
  66. explicit lists:
  67. X: A B Y
  68. Y: A B
  69. Here, A is followed by the set {B,Y} in one list, and {B} in the other
  70. list. The intersection of these sets is {B}, so we can infer that A
  71. depends on at most B. Meanwhile B is followed by the set {Y} in one
  72. list and {} in the other. The intersection is {} so we can infer that
  73. B has no dependencies.
  74. Let's make a more complex example by adding unknown item C and
  75. considering these dependency lists:
  76. X: A B Y C
  77. Y: A C B
  78. The explicit edges are
  79. X -> Y , X -> A , X -> B , X -> C , Y -> A , Y -> B , Y -> C
  80. For the unknown items, we infer dependencies by looking at the
  81. "follow" sets:
  82. A: intersect( {B,Y,C} , {C,B} ) = {B,C} ; infer edges A -> B , A -> C
  83. B: intersect( {Y,C} , {} ) = {} ; infer no edges
  84. C: intersect( {} , {B} ) = {} ; infer no edges
  85. Note that targets are never inferred as dependees because outside
  86. libraries should not depend on them.
  87. ------------------------------------------------------------------------------
  88. The initial exploration of dependencies using a BFS associates an
  89. integer index with each link item. When the graph is built outgoing
  90. edges are sorted by this index.
  91. After the initial exploration of the link interface tree, any
  92. transitive (dependent) shared libraries that were encountered and not
  93. included in the interface are processed in their own BFS. This BFS
  94. follows only the dependent library lists and not the link interfaces.
  95. They are added to the link items with a mark indicating that the are
  96. transitive dependencies. Then cmComputeLinkInformation deals with
  97. them on a per-platform basis.
  98. The complete graph formed from all known and inferred dependencies may
  99. not be acyclic, so an acyclic version must be created.
  100. The original graph is converted to a directed acyclic graph in which
  101. each node corresponds to a strongly connected component of the
  102. original graph. For example, the dependency graph
  103. X -> A -> B -> C -> A -> Y
  104. contains strongly connected components {X}, {A,B,C}, and {Y}. The
  105. implied directed acyclic graph (DAG) is
  106. {X} -> {A,B,C} -> {Y}
  107. We then compute a topological order for the DAG nodes to serve as a
  108. reference for satisfying dependencies efficiently. We perform the DFS
  109. in reverse order and assign topological order indices counting down so
  110. that the result is as close to the original BFS order as possible
  111. without violating dependencies.
  112. ------------------------------------------------------------------------------
  113. The final link entry order is constructed as follows. We first walk
  114. through and emit the *original* link line as specified by the user.
  115. As each item is emitted, a set of pending nodes in the component DAG
  116. is maintained. When a pending component has been completely seen, it
  117. is removed from the pending set and its dependencies (following edges
  118. of the DAG) are added. A trivial component (those with one item) is
  119. complete as soon as its item is seen. A non-trivial component (one
  120. with more than one item; assumed to be static libraries) is complete
  121. when *all* its entries have been seen *twice* (all entries seen once,
  122. then all entries seen again, not just each entry twice). A pending
  123. component tracks which items have been seen and a count of how many
  124. times the component needs to be seen (once for trivial components,
  125. twice for non-trivial). If at any time another component finishes and
  126. re-adds an already pending component, the pending component is reset
  127. so that it needs to be seen in its entirety again. This ensures that
  128. all dependencies of a component are satisfied no matter where it
  129. appears.
  130. After the original link line has been completed, we append to it the
  131. remaining pending components and their dependencies. This is done by
  132. repeatedly emitting the first item from the first pending component
  133. and following the same update rules as when traversing the original
  134. link line. Since the pending components are kept in topological order
  135. they are emitted with minimal repeats (we do not want to emit a
  136. component just to have it added again when another component is
  137. completed later). This process continues until no pending components
  138. remain. We know it will terminate because the component graph is
  139. guaranteed to be acyclic.
  140. The final list of items produced by this procedure consists of the
  141. original user link line followed by minimal additional items needed to
  142. satisfy dependencies. The final list is then filtered to de-duplicate
  143. items that we know the linker will reuse automatically (shared libs).
  144. */
  145. namespace {
  146. // LINK_LIBRARY helpers
  147. const auto LL_BEGIN = "<LINK_LIBRARY:"_s;
  148. const auto LL_END = "</LINK_LIBRARY:"_s;
  149. inline std::string ExtractFeature(std::string const& item)
  150. {
  151. return item.substr(LL_BEGIN.length(),
  152. item.find('>', LL_BEGIN.length()) - LL_BEGIN.length());
  153. }
  154. bool IsFeatureSupported(cmMakefile* makefile, std::string const& linkLanguage,
  155. std::string const& feature)
  156. {
  157. auto featureSupported = cmStrCat(
  158. "CMAKE_", linkLanguage, "_LINK_LIBRARY_USING_", feature, "_SUPPORTED");
  159. if (makefile->GetDefinition(featureSupported).IsOn()) {
  160. return true;
  161. }
  162. featureSupported =
  163. cmStrCat("CMAKE_LINK_LIBRARY_USING_", feature, "_SUPPORTED");
  164. return makefile->GetDefinition(featureSupported).IsOn();
  165. }
  166. // LINK_GROUP helpers
  167. const auto LG_BEGIN = "<LINK_GROUP:"_s;
  168. const auto LG_END = "</LINK_GROUP:"_s;
  169. inline std::string ExtractGroupFeature(std::string const& item)
  170. {
  171. return item.substr(LG_BEGIN.length(),
  172. item.find(':', LG_BEGIN.length()) - LG_BEGIN.length());
  173. }
  174. bool IsGroupFeatureSupported(cmMakefile* makefile,
  175. std::string const& linkLanguage,
  176. std::string const& feature)
  177. {
  178. auto featureSupported = cmStrCat(
  179. "CMAKE_", linkLanguage, "_LINK_GROUP_USING_", feature, "_SUPPORTED");
  180. if (makefile->GetDefinition(featureSupported).IsOn()) {
  181. return true;
  182. }
  183. featureSupported =
  184. cmStrCat("CMAKE_LINK_GROUP_USING_", feature, "_SUPPORTED");
  185. return makefile->GetDefinition(featureSupported).IsOn();
  186. }
  187. }
  188. const std::string cmComputeLinkDepends::LinkEntry::DEFAULT = "DEFAULT";
  189. cmComputeLinkDepends::cmComputeLinkDepends(const cmGeneratorTarget* target,
  190. const std::string& config,
  191. const std::string& linkLanguage)
  192. {
  193. // Store context information.
  194. this->Target = target;
  195. this->Makefile = this->Target->Target->GetMakefile();
  196. this->GlobalGenerator =
  197. this->Target->GetLocalGenerator()->GetGlobalGenerator();
  198. this->CMakeInstance = this->GlobalGenerator->GetCMakeInstance();
  199. this->LinkLanguage = linkLanguage;
  200. // target oriented feature override property takes precedence over
  201. // global override property
  202. cm::string_view lloPrefix = "LINK_LIBRARY_OVERRIDE_"_s;
  203. auto const& keys = this->Target->GetPropertyKeys();
  204. std::for_each(
  205. keys.cbegin(), keys.cend(),
  206. [this, &lloPrefix, &config, &linkLanguage](std::string const& key) {
  207. if (cmHasPrefix(key, lloPrefix)) {
  208. if (cmValue feature = this->Target->GetProperty(key)) {
  209. if (!feature->empty() && key.length() > lloPrefix.length()) {
  210. auto item = key.substr(lloPrefix.length());
  211. cmGeneratorExpressionDAGChecker dag{ this->Target->GetBacktrace(),
  212. this->Target,
  213. "LINK_LIBRARY_OVERRIDE",
  214. nullptr, nullptr };
  215. auto overrideFeature = cmGeneratorExpression::Evaluate(
  216. *feature, this->Target->GetLocalGenerator(), config,
  217. this->Target, &dag, this->Target, linkLanguage);
  218. this->LinkLibraryOverride.emplace(item, overrideFeature);
  219. }
  220. }
  221. }
  222. });
  223. // global override property
  224. if (cmValue linkLibraryOverride =
  225. this->Target->GetProperty("LINK_LIBRARY_OVERRIDE")) {
  226. cmGeneratorExpressionDAGChecker dag{ target->GetBacktrace(), target,
  227. "LINK_LIBRARY_OVERRIDE", nullptr,
  228. nullptr };
  229. auto overrideValue = cmGeneratorExpression::Evaluate(
  230. *linkLibraryOverride, target->GetLocalGenerator(), config, target, &dag,
  231. target, linkLanguage);
  232. auto overrideList = cmTokenize(overrideValue, ","_s);
  233. if (overrideList.size() >= 2) {
  234. auto const& feature = overrideList.front();
  235. for_each(overrideList.cbegin() + 1, overrideList.cend(),
  236. [this, &feature](std::string const& item) {
  237. this->LinkLibraryOverride.emplace(item, feature);
  238. });
  239. }
  240. }
  241. // The configuration being linked.
  242. this->HasConfig = !config.empty();
  243. this->Config = (this->HasConfig) ? config : std::string();
  244. std::vector<std::string> debugConfigs =
  245. this->Makefile->GetCMakeInstance()->GetDebugConfigs();
  246. this->LinkType = CMP0003_ComputeLinkType(this->Config, debugConfigs);
  247. // Enable debug mode if requested.
  248. this->DebugMode = this->Makefile->IsOn("CMAKE_LINK_DEPENDS_DEBUG_MODE");
  249. // Assume no compatibility until set.
  250. this->OldLinkDirMode = false;
  251. // No computation has been done.
  252. this->CCG = nullptr;
  253. }
  254. cmComputeLinkDepends::~cmComputeLinkDepends() = default;
  255. void cmComputeLinkDepends::SetOldLinkDirMode(bool b)
  256. {
  257. this->OldLinkDirMode = b;
  258. }
  259. std::vector<cmComputeLinkDepends::LinkEntry> const&
  260. cmComputeLinkDepends::Compute()
  261. {
  262. // Follow the link dependencies of the target to be linked.
  263. this->AddDirectLinkEntries();
  264. // Complete the breadth-first search of dependencies.
  265. while (!this->BFSQueue.empty()) {
  266. // Get the next entry.
  267. BFSEntry qe = this->BFSQueue.front();
  268. this->BFSQueue.pop();
  269. // Follow the entry's dependencies.
  270. this->FollowLinkEntry(qe);
  271. }
  272. // Complete the search of shared library dependencies.
  273. while (!this->SharedDepQueue.empty()) {
  274. // Handle the next entry.
  275. this->HandleSharedDependency(this->SharedDepQueue.front());
  276. this->SharedDepQueue.pop();
  277. }
  278. // Infer dependencies of targets for which they were not known.
  279. this->InferDependencies();
  280. // finalize groups dependencies
  281. // All dependencies which are raw items must be replaced by the group
  282. // it belongs to, if any.
  283. this->UpdateGroupDependencies();
  284. // Cleanup the constraint graph.
  285. this->CleanConstraintGraph();
  286. // Display the constraint graph.
  287. if (this->DebugMode) {
  288. fprintf(stderr,
  289. "---------------------------------------"
  290. "---------------------------------------\n");
  291. fprintf(stderr, "Link dependency analysis for target %s, config %s\n",
  292. this->Target->GetName().c_str(),
  293. this->HasConfig ? this->Config.c_str() : "noconfig");
  294. this->DisplayConstraintGraph();
  295. }
  296. // Compute the DAG of strongly connected components. The algorithm
  297. // used by cmComputeComponentGraph should identify the components in
  298. // the same order in which the items were originally discovered in
  299. // the BFS. This should preserve the original order when no
  300. // constraints disallow it.
  301. this->CCG =
  302. cm::make_unique<cmComputeComponentGraph>(this->EntryConstraintGraph);
  303. this->CCG->Compute();
  304. if (!this->CheckCircularDependencies()) {
  305. return this->FinalLinkEntries;
  306. }
  307. // Compute the final ordering.
  308. this->OrderLinkEntries();
  309. // Compute the final set of link entries.
  310. // Iterate in reverse order so we can keep only the last occurrence
  311. // of a shared library.
  312. std::set<size_t> emitted;
  313. for (size_t i : cmReverseRange(this->FinalLinkOrder)) {
  314. LinkEntry const& e = this->EntryList[i];
  315. cmGeneratorTarget const* t = e.Target;
  316. // Entries that we know the linker will reuse do not need to be repeated.
  317. bool uniquify = t && t->GetType() == cmStateEnums::SHARED_LIBRARY;
  318. if (!uniquify || emitted.insert(i).second) {
  319. this->FinalLinkEntries.push_back(e);
  320. }
  321. }
  322. // Place explicitly linked object files in the front. The linker will
  323. // always use them anyway, and they may depend on symbols from libraries.
  324. // Append in reverse order since we reverse the final order below.
  325. for (size_t i : cmReverseRange(this->ObjectEntries)) {
  326. this->FinalLinkEntries.emplace_back(this->EntryList[i]);
  327. }
  328. // Reverse the resulting order since we iterated in reverse.
  329. std::reverse(this->FinalLinkEntries.begin(), this->FinalLinkEntries.end());
  330. // Expand group items
  331. if (!this->GroupItems.empty()) {
  332. for (const auto& group : this->GroupItems) {
  333. const LinkEntry& groupEntry = this->EntryList[group.first];
  334. auto it = this->FinalLinkEntries.begin();
  335. while (true) {
  336. it = std::find_if(it, this->FinalLinkEntries.end(),
  337. [&groupEntry](const LinkEntry& entry) -> bool {
  338. return groupEntry.Item == entry.Item;
  339. });
  340. if (it == this->FinalLinkEntries.end()) {
  341. break;
  342. }
  343. it->Item.Value = "</LINK_GROUP>";
  344. for (auto i = group.second.rbegin(); i != group.second.rend(); ++i) {
  345. it = this->FinalLinkEntries.insert(it, this->EntryList[*i]);
  346. }
  347. it = this->FinalLinkEntries.insert(it, groupEntry);
  348. it->Item.Value = "<LINK_GROUP>";
  349. }
  350. }
  351. }
  352. // Display the final set.
  353. if (this->DebugMode) {
  354. this->DisplayFinalEntries();
  355. }
  356. return this->FinalLinkEntries;
  357. }
  358. std::string const& cmComputeLinkDepends::GetCurrentFeature(
  359. std::string const& item, std::string const& defaultFeature) const
  360. {
  361. auto it = this->LinkLibraryOverride.find(item);
  362. return it == this->LinkLibraryOverride.end() ? defaultFeature : it->second;
  363. }
  364. std::pair<std::map<cmLinkItem, size_t>::iterator, bool>
  365. cmComputeLinkDepends::AllocateLinkEntry(cmLinkItem const& item)
  366. {
  367. std::map<cmLinkItem, size_t>::value_type index_entry(
  368. item, static_cast<size_t>(this->EntryList.size()));
  369. auto lei = this->LinkEntryIndex.insert(index_entry);
  370. if (lei.second) {
  371. this->EntryList.emplace_back();
  372. this->InferredDependSets.emplace_back();
  373. this->EntryConstraintGraph.emplace_back();
  374. }
  375. return lei;
  376. }
  377. std::pair<size_t, bool> cmComputeLinkDepends::AddLinkEntry(
  378. cmLinkItem const& item, size_t groupIndex)
  379. {
  380. // Allocate a spot for the item entry.
  381. auto lei = this->AllocateLinkEntry(item);
  382. // Check if the item entry has already been added.
  383. if (!lei.second) {
  384. // Yes. We do not need to follow the item's dependencies again.
  385. return { lei.first->second, false };
  386. }
  387. // Initialize the item entry.
  388. size_t index = lei.first->second;
  389. LinkEntry& entry = this->EntryList[index];
  390. entry.Item = BT<std::string>(item.AsStr(), item.Backtrace);
  391. entry.Target = item.Target;
  392. if (!entry.Target && entry.Item.Value[0] == '-' &&
  393. entry.Item.Value[1] != 'l' &&
  394. entry.Item.Value.substr(0, 10) != "-framework") {
  395. entry.Kind = LinkEntry::Flag;
  396. } else if (cmHasPrefix(entry.Item.Value, LG_BEGIN) &&
  397. cmHasSuffix(entry.Item.Value, '>')) {
  398. entry.Kind = LinkEntry::Group;
  399. }
  400. if (entry.Kind != LinkEntry::Group) {
  401. // If the item has dependencies queue it to follow them.
  402. if (entry.Target) {
  403. // Target dependencies are always known. Follow them.
  404. BFSEntry qe = { index, groupIndex, nullptr };
  405. this->BFSQueue.push(qe);
  406. } else {
  407. // Look for an old-style <item>_LIB_DEPENDS variable.
  408. std::string var = cmStrCat(entry.Item.Value, "_LIB_DEPENDS");
  409. if (cmValue val = this->Makefile->GetDefinition(var)) {
  410. // The item dependencies are known. Follow them.
  411. BFSEntry qe = { index, groupIndex, val->c_str() };
  412. this->BFSQueue.push(qe);
  413. } else if (entry.Kind != LinkEntry::Flag) {
  414. // The item dependencies are not known. We need to infer them.
  415. this->InferredDependSets[index].Initialized = true;
  416. }
  417. }
  418. }
  419. return { index, true };
  420. }
  421. void cmComputeLinkDepends::AddLinkObject(cmLinkItem const& item)
  422. {
  423. assert(!item.Target); // The item is an object file, not its target.
  424. // Allocate a spot for the item entry.
  425. auto lei = this->AllocateLinkEntry(item);
  426. // Check if the item entry has already been added.
  427. if (!lei.second) {
  428. return;
  429. }
  430. // Initialize the item entry.
  431. size_t index = lei.first->second;
  432. LinkEntry& entry = this->EntryList[index];
  433. entry.Item = BT<std::string>(item.AsStr(), item.Backtrace);
  434. entry.Kind = LinkEntry::Object;
  435. // Record explicitly linked object files separately.
  436. this->ObjectEntries.emplace_back(index);
  437. }
  438. void cmComputeLinkDepends::FollowLinkEntry(BFSEntry qe)
  439. {
  440. // Get this entry representation.
  441. size_t depender_index =
  442. qe.GroupIndex == cmComputeComponentGraph::INVALID_COMPONENT
  443. ? qe.Index
  444. : qe.GroupIndex;
  445. LinkEntry const& entry = this->EntryList[qe.Index];
  446. // Follow the item's dependencies.
  447. if (entry.Target) {
  448. // Follow the target dependencies.
  449. if (cmLinkInterface const* iface =
  450. entry.Target->GetLinkInterface(this->Config, this->Target)) {
  451. const bool isIface =
  452. entry.Target->GetType() == cmStateEnums::INTERFACE_LIBRARY;
  453. // This target provides its own link interface information.
  454. this->AddLinkEntries(depender_index, iface->Libraries);
  455. this->AddLinkObjects(iface->Objects);
  456. for (auto const& language : iface->Languages) {
  457. auto runtimeEntries = iface->LanguageRuntimeLibraries.find(language);
  458. if (runtimeEntries != iface->LanguageRuntimeLibraries.end()) {
  459. this->AddLinkEntries(depender_index, runtimeEntries->second);
  460. }
  461. }
  462. if (isIface) {
  463. return;
  464. }
  465. // Handle dependent shared libraries.
  466. this->FollowSharedDeps(depender_index, iface);
  467. // Support for CMP0003.
  468. for (cmLinkItem const& oi : iface->WrongConfigLibraries) {
  469. this->CheckWrongConfigItem(oi);
  470. }
  471. }
  472. } else {
  473. // Follow the old-style dependency list.
  474. this->AddVarLinkEntries(depender_index, qe.LibDepends);
  475. }
  476. }
  477. void cmComputeLinkDepends::FollowSharedDeps(size_t depender_index,
  478. cmLinkInterface const* iface,
  479. bool follow_interface)
  480. {
  481. // Follow dependencies if we have not followed them already.
  482. if (this->SharedDepFollowed.insert(depender_index).second) {
  483. if (follow_interface) {
  484. this->QueueSharedDependencies(depender_index, iface->Libraries);
  485. }
  486. this->QueueSharedDependencies(depender_index, iface->SharedDeps);
  487. }
  488. }
  489. void cmComputeLinkDepends::QueueSharedDependencies(
  490. size_t depender_index, std::vector<cmLinkItem> const& deps)
  491. {
  492. for (cmLinkItem const& li : deps) {
  493. SharedDepEntry qe;
  494. qe.Item = li;
  495. qe.DependerIndex = depender_index;
  496. this->SharedDepQueue.push(qe);
  497. }
  498. }
  499. void cmComputeLinkDepends::HandleSharedDependency(SharedDepEntry const& dep)
  500. {
  501. // Allocate a spot for the item entry.
  502. auto lei = this->AllocateLinkEntry(dep.Item);
  503. size_t index = lei.first->second;
  504. // Check if the target does not already has an entry.
  505. if (lei.second) {
  506. // Initialize the item entry.
  507. LinkEntry& entry = this->EntryList[index];
  508. entry.Item = BT<std::string>(dep.Item.AsStr(), dep.Item.Backtrace);
  509. entry.Target = dep.Item.Target;
  510. // This item was added specifically because it is a dependent
  511. // shared library. It may get special treatment
  512. // in cmComputeLinkInformation.
  513. entry.Kind = LinkEntry::SharedDep;
  514. }
  515. // Get the link entry for this target.
  516. LinkEntry& entry = this->EntryList[index];
  517. // This shared library dependency must follow the item that listed
  518. // it.
  519. this->EntryConstraintGraph[dep.DependerIndex].emplace_back(
  520. index, true, false, cmListFileBacktrace());
  521. // Target items may have their own dependencies.
  522. if (entry.Target) {
  523. if (cmLinkInterface const* iface =
  524. entry.Target->GetLinkInterface(this->Config, this->Target)) {
  525. // Follow public and private dependencies transitively.
  526. this->FollowSharedDeps(index, iface, true);
  527. }
  528. }
  529. }
  530. void cmComputeLinkDepends::AddVarLinkEntries(size_t depender_index,
  531. const char* value)
  532. {
  533. // This is called to add the dependencies named by
  534. // <item>_LIB_DEPENDS. The variable contains a semicolon-separated
  535. // list. The list contains link-type;item pairs and just items.
  536. cmList deplist{ value };
  537. // Look for entries meant for this configuration.
  538. std::vector<cmLinkItem> actual_libs;
  539. cmTargetLinkLibraryType llt = GENERAL_LibraryType;
  540. bool haveLLT = false;
  541. for (std::string const& d : deplist) {
  542. if (d == "debug") {
  543. llt = DEBUG_LibraryType;
  544. haveLLT = true;
  545. } else if (d == "optimized") {
  546. llt = OPTIMIZED_LibraryType;
  547. haveLLT = true;
  548. } else if (d == "general") {
  549. llt = GENERAL_LibraryType;
  550. haveLLT = true;
  551. } else if (!d.empty()) {
  552. // If no explicit link type was given prior to this entry then
  553. // check if the entry has its own link type variable. This is
  554. // needed for compatibility with dependency files generated by
  555. // the export_library_dependencies command from CMake 2.4 and
  556. // lower.
  557. if (!haveLLT) {
  558. std::string var = cmStrCat(d, "_LINK_TYPE");
  559. if (cmValue val = this->Makefile->GetDefinition(var)) {
  560. if (*val == "debug") {
  561. llt = DEBUG_LibraryType;
  562. } else if (*val == "optimized") {
  563. llt = OPTIMIZED_LibraryType;
  564. }
  565. }
  566. }
  567. // If the library is meant for this link type then use it.
  568. if (llt == GENERAL_LibraryType || llt == this->LinkType) {
  569. actual_libs.emplace_back(this->ResolveLinkItem(depender_index, d));
  570. } else if (this->OldLinkDirMode) {
  571. cmLinkItem item = this->ResolveLinkItem(depender_index, d);
  572. this->CheckWrongConfigItem(item);
  573. }
  574. // Reset the link type until another explicit type is given.
  575. llt = GENERAL_LibraryType;
  576. haveLLT = false;
  577. }
  578. }
  579. // Add the entries from this list.
  580. this->AddLinkEntries(depender_index, actual_libs);
  581. }
  582. void cmComputeLinkDepends::AddDirectLinkEntries()
  583. {
  584. // Add direct link dependencies in this configuration.
  585. cmLinkImplementation const* impl = this->Target->GetLinkImplementation(
  586. this->Config, cmGeneratorTarget::LinkInterfaceFor::Link);
  587. this->AddLinkEntries(cmComputeComponentGraph::INVALID_COMPONENT,
  588. impl->Libraries);
  589. this->AddLinkObjects(impl->Objects);
  590. for (auto const& language : impl->Languages) {
  591. auto runtimeEntries = impl->LanguageRuntimeLibraries.find(language);
  592. if (runtimeEntries != impl->LanguageRuntimeLibraries.end()) {
  593. this->AddLinkEntries(cmComputeComponentGraph::INVALID_COMPONENT,
  594. runtimeEntries->second);
  595. }
  596. }
  597. for (cmLinkItem const& wi : impl->WrongConfigLibraries) {
  598. this->CheckWrongConfigItem(wi);
  599. }
  600. }
  601. template <typename T>
  602. void cmComputeLinkDepends::AddLinkEntries(size_t depender_index,
  603. std::vector<T> const& libs)
  604. {
  605. // Track inferred dependency sets implied by this list.
  606. std::map<size_t, DependSet> dependSets;
  607. std::string feature = LinkEntry::DEFAULT;
  608. bool inGroup = false;
  609. std::pair<size_t, bool> groupIndex{
  610. cmComputeComponentGraph::INVALID_COMPONENT, false
  611. };
  612. std::vector<size_t> groupItems;
  613. // Loop over the libraries linked directly by the depender.
  614. for (T const& l : libs) {
  615. // Skip entries that will resolve to the target getting linked or
  616. // are empty.
  617. cmLinkItem const& item = l;
  618. if (item.AsStr() == this->Target->GetName() || item.AsStr().empty()) {
  619. continue;
  620. }
  621. if (cmHasPrefix(item.AsStr(), LL_BEGIN) &&
  622. cmHasSuffix(item.AsStr(), '>')) {
  623. feature = ExtractFeature(item.AsStr());
  624. // emit a warning if an undefined feature is used as part of
  625. // an imported target
  626. if (depender_index != cmComputeComponentGraph::INVALID_COMPONENT) {
  627. const auto& depender = this->EntryList[depender_index];
  628. if (depender.Target != nullptr && depender.Target->IsImported() &&
  629. !IsFeatureSupported(this->Makefile, this->LinkLanguage, feature)) {
  630. this->CMakeInstance->IssueMessage(
  631. MessageType::AUTHOR_ERROR,
  632. cmStrCat("The 'IMPORTED' target '", depender.Target->GetName(),
  633. "' uses the generator-expression '$<LINK_LIBRARY>' with "
  634. "the feature '",
  635. feature,
  636. "', which is undefined or unsupported.\nDid you miss to "
  637. "define it by setting variables \"CMAKE_",
  638. this->LinkLanguage, "_LINK_LIBRARY_USING_", feature,
  639. "\" and \"CMAKE_", this->LinkLanguage,
  640. "_LINK_LIBRARY_USING_", feature, "_SUPPORTED\"?"),
  641. this->Target->GetBacktrace());
  642. }
  643. }
  644. continue;
  645. }
  646. if (cmHasPrefix(item.AsStr(), LL_END) && cmHasSuffix(item.AsStr(), '>')) {
  647. feature = LinkEntry::DEFAULT;
  648. continue;
  649. }
  650. if (cmHasPrefix(item.AsStr(), LG_BEGIN) &&
  651. cmHasSuffix(item.AsStr(), '>')) {
  652. groupIndex = this->AddLinkEntry(item);
  653. if (groupIndex.second) {
  654. LinkEntry& entry = this->EntryList[groupIndex.first];
  655. entry.Feature = ExtractGroupFeature(item.AsStr());
  656. }
  657. inGroup = true;
  658. if (depender_index != cmComputeComponentGraph::INVALID_COMPONENT) {
  659. this->EntryConstraintGraph[depender_index].emplace_back(
  660. groupIndex.first, false, false, cmListFileBacktrace());
  661. } else {
  662. // This is a direct dependency of the target being linked.
  663. this->OriginalEntries.push_back(groupIndex.first);
  664. }
  665. continue;
  666. }
  667. size_t dependee_index;
  668. if (cmHasPrefix(item.AsStr(), LG_END) && cmHasSuffix(item.AsStr(), '>')) {
  669. dependee_index = groupIndex.first;
  670. if (groupIndex.second) {
  671. this->GroupItems.emplace(groupIndex.first, groupItems);
  672. }
  673. inGroup = false;
  674. groupIndex = std::make_pair(-1, false);
  675. groupItems.clear();
  676. continue;
  677. }
  678. if (depender_index != cmComputeComponentGraph::INVALID_COMPONENT &&
  679. inGroup) {
  680. const auto& depender = this->EntryList[depender_index];
  681. const auto& groupFeature = this->EntryList[groupIndex.first].Feature;
  682. if (depender.Target != nullptr && depender.Target->IsImported() &&
  683. !IsGroupFeatureSupported(this->Makefile, this->LinkLanguage,
  684. groupFeature)) {
  685. this->CMakeInstance->IssueMessage(
  686. MessageType::AUTHOR_ERROR,
  687. cmStrCat("The 'IMPORTED' target '", depender.Target->GetName(),
  688. "' uses the generator-expression '$<LINK_GROUP>' with "
  689. "the feature '",
  690. groupFeature,
  691. "', which is undefined or unsupported.\nDid you miss to "
  692. "define it by setting variables \"CMAKE_",
  693. this->LinkLanguage, "_LINK_GROUP_USING_", groupFeature,
  694. "\" and \"CMAKE_", this->LinkLanguage, "_LINK_GROUP_USING_",
  695. groupFeature, "_SUPPORTED\"?"),
  696. this->Target->GetBacktrace());
  697. }
  698. }
  699. // Add a link entry for this item.
  700. auto ale = this->AddLinkEntry(item, groupIndex.first);
  701. dependee_index = ale.first;
  702. LinkEntry& entry = this->EntryList[dependee_index];
  703. auto const& itemFeature =
  704. this->GetCurrentFeature(entry.Item.Value, feature);
  705. if (inGroup && ale.second && entry.Target != nullptr &&
  706. (entry.Target->GetType() == cmStateEnums::TargetType::OBJECT_LIBRARY ||
  707. entry.Target->GetType() ==
  708. cmStateEnums::TargetType::INTERFACE_LIBRARY)) {
  709. const auto& groupFeature = this->EntryList[groupIndex.first].Feature;
  710. this->CMakeInstance->IssueMessage(
  711. MessageType::AUTHOR_WARNING,
  712. cmStrCat(
  713. "The feature '", groupFeature,
  714. "', specified as part of a generator-expression "
  715. "'$",
  716. LG_BEGIN, groupFeature, ">', will not be applied to the ",
  717. (entry.Target->GetType() == cmStateEnums::TargetType::OBJECT_LIBRARY
  718. ? "OBJECT"
  719. : "INTERFACE"),
  720. " library '", entry.Item.Value, "'."),
  721. this->Target->GetBacktrace());
  722. }
  723. if (itemFeature != LinkEntry::DEFAULT) {
  724. if (ale.second) {
  725. // current item not yet defined
  726. if (entry.Target != nullptr &&
  727. (entry.Target->GetType() ==
  728. cmStateEnums::TargetType::OBJECT_LIBRARY ||
  729. entry.Target->GetType() ==
  730. cmStateEnums::TargetType::INTERFACE_LIBRARY)) {
  731. this->CMakeInstance->IssueMessage(
  732. MessageType::AUTHOR_WARNING,
  733. cmStrCat("The feature '", feature,
  734. "', specified as part of a generator-expression "
  735. "'$",
  736. LL_BEGIN, feature, ">', will not be applied to the ",
  737. (entry.Target->GetType() ==
  738. cmStateEnums::TargetType::OBJECT_LIBRARY
  739. ? "OBJECT"
  740. : "INTERFACE"),
  741. " library '", entry.Item.Value, "'."),
  742. this->Target->GetBacktrace());
  743. } else {
  744. entry.Feature = itemFeature;
  745. }
  746. }
  747. }
  748. bool supportedItem = entry.Target == nullptr ||
  749. (entry.Target->GetType() != cmStateEnums::TargetType::OBJECT_LIBRARY &&
  750. entry.Target->GetType() != cmStateEnums::TargetType::INTERFACE_LIBRARY);
  751. if (supportedItem) {
  752. if (inGroup) {
  753. const auto& currentFeature = this->EntryList[groupIndex.first].Feature;
  754. for (const auto& g : this->GroupItems) {
  755. const auto& groupFeature = this->EntryList[g.first].Feature;
  756. if (groupFeature == currentFeature) {
  757. continue;
  758. }
  759. if (std::find(g.second.cbegin(), g.second.cend(), dependee_index) !=
  760. g.second.cend()) {
  761. this->CMakeInstance->IssueMessage(
  762. MessageType::FATAL_ERROR,
  763. cmStrCat("Impossible to link target '", this->Target->GetName(),
  764. "' because the link item '", entry.Item.Value,
  765. "', specified with the group feature '", currentFeature,
  766. '\'', ", has already occurred with the feature '",
  767. groupFeature, '\'', ", which is not allowed."),
  768. this->Target->GetBacktrace());
  769. continue;
  770. }
  771. }
  772. }
  773. if (entry.Feature != itemFeature) {
  774. // incompatibles features occurred
  775. this->CMakeInstance->IssueMessage(
  776. MessageType::FATAL_ERROR,
  777. cmStrCat("Impossible to link target '", this->Target->GetName(),
  778. "' because the link item '", entry.Item.Value,
  779. "', specified ",
  780. (itemFeature == LinkEntry::DEFAULT
  781. ? "without any feature or 'DEFAULT' feature"
  782. : cmStrCat("with the feature '", itemFeature, '\'')),
  783. ", has already occurred ",
  784. (entry.Feature == LinkEntry::DEFAULT
  785. ? "without any feature or 'DEFAULT' feature"
  786. : cmStrCat("with the feature '", entry.Feature, '\'')),
  787. ", which is not allowed."),
  788. this->Target->GetBacktrace());
  789. }
  790. }
  791. if (inGroup) {
  792. // store item index for dependencies handling
  793. groupItems.push_back(dependee_index);
  794. } else {
  795. std::vector<size_t> indexes;
  796. bool entryHandled = false;
  797. // search any occurrence of the library in already defined groups
  798. for (const auto& group : this->GroupItems) {
  799. for (auto index : group.second) {
  800. if (entry.Item.Value == this->EntryList[index].Item.Value) {
  801. indexes.push_back(group.first);
  802. entryHandled = true;
  803. break;
  804. }
  805. }
  806. }
  807. if (!entryHandled) {
  808. indexes.push_back(dependee_index);
  809. }
  810. for (auto index : indexes) {
  811. // The dependee must come after the depender.
  812. if (depender_index != cmComputeComponentGraph::INVALID_COMPONENT) {
  813. this->EntryConstraintGraph[depender_index].emplace_back(
  814. index, false, false, cmListFileBacktrace());
  815. } else {
  816. // This is a direct dependency of the target being linked.
  817. this->OriginalEntries.push_back(index);
  818. }
  819. // Update the inferred dependencies for earlier items.
  820. for (auto& dependSet : dependSets) {
  821. // Add this item to the inferred dependencies of other items.
  822. // Target items are never inferred dependees because unknown
  823. // items are outside libraries that should not be depending on
  824. // targets.
  825. if (!this->EntryList[index].Target &&
  826. this->EntryList[index].Kind != LinkEntry::Flag &&
  827. this->EntryList[index].Kind != LinkEntry::Group &&
  828. dependee_index != dependSet.first) {
  829. dependSet.second.insert(index);
  830. }
  831. }
  832. // If this item needs to have dependencies inferred, do so.
  833. if (this->InferredDependSets[index].Initialized) {
  834. // Make sure an entry exists to hold the set for the item.
  835. dependSets[index];
  836. }
  837. }
  838. }
  839. }
  840. // Store the inferred dependency sets discovered for this list.
  841. for (auto const& dependSet : dependSets) {
  842. this->InferredDependSets[dependSet.first].push_back(dependSet.second);
  843. }
  844. }
  845. void cmComputeLinkDepends::AddLinkObjects(std::vector<cmLinkItem> const& objs)
  846. {
  847. for (cmLinkItem const& obj : objs) {
  848. this->AddLinkObject(obj);
  849. }
  850. }
  851. cmLinkItem cmComputeLinkDepends::ResolveLinkItem(size_t depender_index,
  852. const std::string& name)
  853. {
  854. // Look for a target in the scope of the depender.
  855. cmGeneratorTarget const* from = this->Target;
  856. if (depender_index != cmComputeComponentGraph::INVALID_COMPONENT) {
  857. if (cmGeneratorTarget const* depender =
  858. this->EntryList[depender_index].Target) {
  859. from = depender;
  860. }
  861. }
  862. return from->ResolveLinkItem(BT<std::string>(name));
  863. }
  864. void cmComputeLinkDepends::InferDependencies()
  865. {
  866. // The inferred dependency sets for each item list the possible
  867. // dependencies. The intersection of the sets for one item form its
  868. // inferred dependencies.
  869. for (size_t depender_index = 0;
  870. depender_index < this->InferredDependSets.size(); ++depender_index) {
  871. // Skip items for which dependencies do not need to be inferred or
  872. // for which the inferred dependency sets are empty.
  873. DependSetList& sets = this->InferredDependSets[depender_index];
  874. if (!sets.Initialized || sets.empty()) {
  875. continue;
  876. }
  877. // Intersect the sets for this item.
  878. DependSet common = sets.front();
  879. for (DependSet const& i : cmMakeRange(sets).advance(1)) {
  880. DependSet intersection;
  881. std::set_intersection(common.begin(), common.end(), i.begin(), i.end(),
  882. std::inserter(intersection, intersection.begin()));
  883. common = intersection;
  884. }
  885. // Add the inferred dependencies to the graph.
  886. cmGraphEdgeList& edges = this->EntryConstraintGraph[depender_index];
  887. edges.reserve(edges.size() + common.size());
  888. for (auto const& c : common) {
  889. edges.emplace_back(c, true, false, cmListFileBacktrace());
  890. }
  891. }
  892. }
  893. void cmComputeLinkDepends::UpdateGroupDependencies()
  894. {
  895. if (this->GroupItems.empty()) {
  896. return;
  897. }
  898. // Walks through all entries of the constraint graph to replace dependencies
  899. // over raw items by the group it belongs to, if any.
  900. for (auto& edgeList : this->EntryConstraintGraph) {
  901. for (auto& edge : edgeList) {
  902. size_t index = edge;
  903. if (this->EntryList[index].Kind == LinkEntry::Group ||
  904. this->EntryList[index].Kind == LinkEntry::Flag ||
  905. this->EntryList[index].Kind == LinkEntry::Object) {
  906. continue;
  907. }
  908. // search the item in the defined groups
  909. for (const auto& groupItems : this->GroupItems) {
  910. auto pos = std::find(groupItems.second.cbegin(),
  911. groupItems.second.cend(), index);
  912. if (pos != groupItems.second.cend()) {
  913. // replace lib dependency by the group it belongs to
  914. edge = cmGraphEdge{ groupItems.first, false, false,
  915. cmListFileBacktrace() };
  916. }
  917. }
  918. }
  919. }
  920. }
  921. void cmComputeLinkDepends::CleanConstraintGraph()
  922. {
  923. for (cmGraphEdgeList& edgeList : this->EntryConstraintGraph) {
  924. // Sort the outgoing edges for each graph node so that the
  925. // original order will be preserved as much as possible.
  926. std::sort(edgeList.begin(), edgeList.end());
  927. // Make the edge list unique.
  928. edgeList.erase(std::unique(edgeList.begin(), edgeList.end()),
  929. edgeList.end());
  930. }
  931. }
  932. bool cmComputeLinkDepends::CheckCircularDependencies() const
  933. {
  934. std::vector<NodeList> const& components = this->CCG->GetComponents();
  935. size_t nc = components.size();
  936. for (size_t c = 0; c < nc; ++c) {
  937. // Get the current component.
  938. NodeList const& nl = components[c];
  939. // Skip trivial components.
  940. if (nl.size() < 2) {
  941. continue;
  942. }
  943. // no group must be evolved
  944. bool cycleDetected = false;
  945. for (size_t ni : nl) {
  946. if (this->EntryList[ni].Kind == LinkEntry::Group) {
  947. cycleDetected = true;
  948. break;
  949. }
  950. }
  951. if (!cycleDetected) {
  952. continue;
  953. }
  954. // Construct the error message.
  955. auto formatItem = [](LinkEntry const& entry) -> std::string {
  956. if (entry.Kind == LinkEntry::Group) {
  957. auto items =
  958. entry.Item.Value.substr(entry.Item.Value.find(':', 12) + 1);
  959. items.pop_back();
  960. std::replace(items.begin(), items.end(), '|', ',');
  961. return cmStrCat("group \"", ExtractGroupFeature(entry.Item.Value),
  962. ":{", items, "}\"");
  963. }
  964. return cmStrCat('"', entry.Item.Value, '"');
  965. };
  966. std::ostringstream e;
  967. e << "The inter-target dependency graph, for the target \""
  968. << this->Target->GetName()
  969. << "\", contains the following strongly connected component "
  970. "(cycle):\n";
  971. std::vector<size_t> const& cmap = this->CCG->GetComponentMap();
  972. for (size_t i : nl) {
  973. // Get the depender.
  974. LinkEntry const& depender = this->EntryList[i];
  975. // Describe the depender.
  976. e << " " << formatItem(depender) << "\n";
  977. // List its dependencies that are inside the component.
  978. EdgeList const& el = this->EntryConstraintGraph[i];
  979. for (cmGraphEdge const& ni : el) {
  980. size_t j = ni;
  981. if (cmap[j] == c) {
  982. LinkEntry const& dependee = this->EntryList[j];
  983. e << " depends on " << formatItem(dependee) << "\n";
  984. }
  985. }
  986. }
  987. this->CMakeInstance->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  988. this->Target->GetBacktrace());
  989. return false;
  990. }
  991. return true;
  992. }
  993. void cmComputeLinkDepends::DisplayConstraintGraph()
  994. {
  995. // Display the graph nodes and their edges.
  996. std::ostringstream e;
  997. for (size_t i = 0; i < this->EntryConstraintGraph.size(); ++i) {
  998. EdgeList const& nl = this->EntryConstraintGraph[i];
  999. e << "item " << i << " is [" << this->EntryList[i].Item << "]\n";
  1000. e << cmWrap(" item ", nl, " must follow it", "\n") << "\n";
  1001. }
  1002. fprintf(stderr, "%s\n", e.str().c_str());
  1003. }
  1004. void cmComputeLinkDepends::OrderLinkEntries()
  1005. {
  1006. // The component graph is guaranteed to be acyclic. Start a DFS
  1007. // from every entry to compute a topological order for the
  1008. // components.
  1009. Graph const& cgraph = this->CCG->GetComponentGraph();
  1010. size_t n = cgraph.size();
  1011. this->ComponentVisited.resize(cgraph.size(), 0);
  1012. this->ComponentOrder.resize(cgraph.size(), n);
  1013. this->ComponentOrderId = n;
  1014. // Run in reverse order so the topological order will preserve the
  1015. // original order where there are no constraints.
  1016. for (size_t c = n - 1; c != cmComputeComponentGraph::INVALID_COMPONENT;
  1017. --c) {
  1018. this->VisitComponent(c);
  1019. }
  1020. // Display the component graph.
  1021. if (this->DebugMode) {
  1022. this->DisplayComponents();
  1023. }
  1024. // Start with the original link line.
  1025. for (size_t originalEntry : this->OriginalEntries) {
  1026. this->VisitEntry(originalEntry);
  1027. }
  1028. // Now explore anything left pending. Since the component graph is
  1029. // guaranteed to be acyclic we know this will terminate.
  1030. while (!this->PendingComponents.empty()) {
  1031. // Visit one entry from the first pending component. The visit
  1032. // logic will update the pending components accordingly. Since
  1033. // the pending components are kept in topological order this will
  1034. // not repeat one.
  1035. size_t e = *this->PendingComponents.begin()->second.Entries.begin();
  1036. this->VisitEntry(e);
  1037. }
  1038. }
  1039. void cmComputeLinkDepends::DisplayComponents()
  1040. {
  1041. fprintf(stderr, "The strongly connected components are:\n");
  1042. std::vector<NodeList> const& components = this->CCG->GetComponents();
  1043. for (size_t c = 0; c < components.size(); ++c) {
  1044. fprintf(stderr, "Component (%zu):\n", c);
  1045. NodeList const& nl = components[c];
  1046. for (size_t i : nl) {
  1047. fprintf(stderr, " item %zu [%s]\n", i,
  1048. this->EntryList[i].Item.Value.c_str());
  1049. }
  1050. EdgeList const& ol = this->CCG->GetComponentGraphEdges(c);
  1051. for (cmGraphEdge const& oi : ol) {
  1052. size_t i = oi;
  1053. fprintf(stderr, " followed by Component (%zu)\n", i);
  1054. }
  1055. fprintf(stderr, " topo order index %zu\n", this->ComponentOrder[c]);
  1056. }
  1057. fprintf(stderr, "\n");
  1058. }
  1059. void cmComputeLinkDepends::VisitComponent(size_t c)
  1060. {
  1061. // Check if the node has already been visited.
  1062. if (this->ComponentVisited[c]) {
  1063. return;
  1064. }
  1065. // We are now visiting this component so mark it.
  1066. this->ComponentVisited[c] = 1;
  1067. // Visit the neighbors of the component first.
  1068. // Run in reverse order so the topological order will preserve the
  1069. // original order where there are no constraints.
  1070. EdgeList const& nl = this->CCG->GetComponentGraphEdges(c);
  1071. for (cmGraphEdge const& edge : cmReverseRange(nl)) {
  1072. this->VisitComponent(edge);
  1073. }
  1074. // Assign an ordering id to this component.
  1075. this->ComponentOrder[c] = --this->ComponentOrderId;
  1076. }
  1077. void cmComputeLinkDepends::VisitEntry(size_t index)
  1078. {
  1079. // Include this entry on the link line.
  1080. this->FinalLinkOrder.push_back(index);
  1081. // This entry has now been seen. Update its component.
  1082. bool completed = false;
  1083. size_t component = this->CCG->GetComponentMap()[index];
  1084. auto mi = this->PendingComponents.find(this->ComponentOrder[component]);
  1085. if (mi != this->PendingComponents.end()) {
  1086. // The entry is in an already pending component.
  1087. PendingComponent& pc = mi->second;
  1088. // Remove the entry from those pending in its component.
  1089. pc.Entries.erase(index);
  1090. if (pc.Entries.empty()) {
  1091. // The complete component has been seen since it was last needed.
  1092. --pc.Count;
  1093. if (pc.Count == 0) {
  1094. // The component has been completed.
  1095. this->PendingComponents.erase(mi);
  1096. completed = true;
  1097. } else {
  1098. // The whole component needs to be seen again.
  1099. NodeList const& nl = this->CCG->GetComponent(component);
  1100. assert(nl.size() > 1);
  1101. pc.Entries.insert(nl.begin(), nl.end());
  1102. }
  1103. }
  1104. } else {
  1105. // The entry is not in an already pending component.
  1106. NodeList const& nl = this->CCG->GetComponent(component);
  1107. if (nl.size() > 1) {
  1108. // This is a non-trivial component. It is now pending.
  1109. PendingComponent& pc = this->MakePendingComponent(component);
  1110. // The starting entry has already been seen.
  1111. pc.Entries.erase(index);
  1112. } else {
  1113. // This is a trivial component, so it is already complete.
  1114. completed = true;
  1115. }
  1116. }
  1117. // If the entry completed a component, the component's dependencies
  1118. // are now pending.
  1119. if (completed) {
  1120. EdgeList const& ol = this->CCG->GetComponentGraphEdges(component);
  1121. for (cmGraphEdge const& oi : ol) {
  1122. // This entire component is now pending no matter whether it has
  1123. // been partially seen already.
  1124. this->MakePendingComponent(oi);
  1125. }
  1126. }
  1127. }
  1128. cmComputeLinkDepends::PendingComponent&
  1129. cmComputeLinkDepends::MakePendingComponent(size_t component)
  1130. {
  1131. // Create an entry (in topological order) for the component.
  1132. PendingComponent& pc =
  1133. this->PendingComponents[this->ComponentOrder[component]];
  1134. pc.Id = component;
  1135. NodeList const& nl = this->CCG->GetComponent(component);
  1136. if (nl.size() == 1) {
  1137. // Trivial components need be seen only once.
  1138. pc.Count = 1;
  1139. } else {
  1140. // This is a non-trivial strongly connected component of the
  1141. // original graph. It consists of two or more libraries
  1142. // (archives) that mutually require objects from one another. In
  1143. // the worst case we may have to repeat the list of libraries as
  1144. // many times as there are object files in the biggest archive.
  1145. // For now we just list them twice.
  1146. //
  1147. // The list of items in the component has been sorted by the order
  1148. // of discovery in the original BFS of dependencies. This has the
  1149. // advantage that the item directly linked by a target requiring
  1150. // this component will come first which minimizes the number of
  1151. // repeats needed.
  1152. pc.Count = this->ComputeComponentCount(nl);
  1153. }
  1154. // Store the entries to be seen.
  1155. pc.Entries.insert(nl.begin(), nl.end());
  1156. return pc;
  1157. }
  1158. size_t cmComputeLinkDepends::ComputeComponentCount(NodeList const& nl)
  1159. {
  1160. size_t count = 2;
  1161. for (size_t ni : nl) {
  1162. if (cmGeneratorTarget const* target = this->EntryList[ni].Target) {
  1163. if (cmLinkInterface const* iface =
  1164. target->GetLinkInterface(this->Config, this->Target)) {
  1165. if (iface->Multiplicity > count) {
  1166. count = iface->Multiplicity;
  1167. }
  1168. }
  1169. }
  1170. }
  1171. return count;
  1172. }
  1173. void cmComputeLinkDepends::DisplayFinalEntries()
  1174. {
  1175. fprintf(stderr, "target [%s] links to:\n", this->Target->GetName().c_str());
  1176. char space[] = " ";
  1177. int count = 2;
  1178. for (LinkEntry const& lei : this->FinalLinkEntries) {
  1179. if (lei.Kind == LinkEntry::Group) {
  1180. fprintf(stderr, " %s group",
  1181. lei.Item.Value == "<LINK_GROUP>" ? "start" : "end");
  1182. count = lei.Item.Value == "<LINK_GROUP>" ? 4 : 2;
  1183. } else if (lei.Target) {
  1184. fprintf(stderr, "%*starget [%s]", count, space,
  1185. lei.Target->GetName().c_str());
  1186. } else {
  1187. fprintf(stderr, "%*sitem [%s]", count, space, lei.Item.Value.c_str());
  1188. }
  1189. if (lei.Feature != LinkEntry::DEFAULT) {
  1190. fprintf(stderr, ", feature [%s]", lei.Feature.c_str());
  1191. }
  1192. fprintf(stderr, "\n");
  1193. }
  1194. fprintf(stderr, "\n");
  1195. }
  1196. void cmComputeLinkDepends::CheckWrongConfigItem(cmLinkItem const& item)
  1197. {
  1198. if (!this->OldLinkDirMode) {
  1199. return;
  1200. }
  1201. // For CMake 2.4 bug-compatibility we need to consider the output
  1202. // directories of targets linked in another configuration as link
  1203. // directories.
  1204. if (item.Target && !item.Target->IsImported()) {
  1205. this->OldWrongConfigItems.insert(item.Target);
  1206. }
  1207. }