cmComputeLinkDepends.cxx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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 "cmAlgorithms.h"
  5. #include "cmComputeComponentGraph.h"
  6. #include "cmGeneratorTarget.h"
  7. #include "cmGlobalGenerator.h"
  8. #include "cmLocalGenerator.h"
  9. #include "cmMakefile.h"
  10. #include "cmStateTypes.h"
  11. #include "cmSystemTools.h"
  12. #include "cmTarget.h"
  13. #include "cmake.h"
  14. #include <algorithm>
  15. #include <assert.h>
  16. #include <iterator>
  17. #include <sstream>
  18. #include <stdio.h>
  19. #include <string.h>
  20. #include <utility>
  21. /*
  22. This file computes an ordered list of link items to use when linking a
  23. single target in one configuration. Each link item is identified by
  24. the string naming it. A graph of dependencies is created in which
  25. each node corresponds to one item and directed edges lead from nodes to
  26. those which must *follow* them on the link line. For example, the
  27. graph
  28. A -> B -> C
  29. will lead to the link line order
  30. A B C
  31. The set of items placed in the graph is formed with a breadth-first
  32. search of the link dependencies starting from the main target.
  33. There are two types of items: those with known direct dependencies and
  34. those without known dependencies. We will call the two types "known
  35. items" and "unknown items", respectively. Known items are those whose
  36. names correspond to targets (built or imported) and those for which an
  37. old-style <item>_LIB_DEPENDS variable is defined. All other items are
  38. unknown and we must infer dependencies for them. For items that look
  39. like flags (beginning with '-') we trivially infer no dependencies,
  40. and do not include them in the dependencies of other items.
  41. Known items have dependency lists ordered based on how the user
  42. specified them. We can use this order to infer potential dependencies
  43. of unknown items. For example, if link items A and B are unknown and
  44. items X and Y are known, then we might have the following dependency
  45. lists:
  46. X: Y A B
  47. Y: A B
  48. The explicitly known dependencies form graph edges
  49. X -> Y , X -> A , X -> B , Y -> A , Y -> B
  50. We can also infer the edge
  51. A -> B
  52. because *every* time A appears B is seen on its right. We do not know
  53. whether A really needs symbols from B to link, but it *might* so we
  54. must preserve their order. This is the case also for the following
  55. explicit lists:
  56. X: A B Y
  57. Y: A B
  58. Here, A is followed by the set {B,Y} in one list, and {B} in the other
  59. list. The intersection of these sets is {B}, so we can infer that A
  60. depends on at most B. Meanwhile B is followed by the set {Y} in one
  61. list and {} in the other. The intersection is {} so we can infer that
  62. B has no dependencies.
  63. Let's make a more complex example by adding unknown item C and
  64. considering these dependency lists:
  65. X: A B Y C
  66. Y: A C B
  67. The explicit edges are
  68. X -> Y , X -> A , X -> B , X -> C , Y -> A , Y -> B , Y -> C
  69. For the unknown items, we infer dependencies by looking at the
  70. "follow" sets:
  71. A: intersect( {B,Y,C} , {C,B} ) = {B,C} ; infer edges A -> B , A -> C
  72. B: intersect( {Y,C} , {} ) = {} ; infer no edges
  73. C: intersect( {} , {B} ) = {} ; infer no edges
  74. Note that targets are never inferred as dependees because outside
  75. libraries should not depend on them.
  76. ------------------------------------------------------------------------------
  77. The initial exploration of dependencies using a BFS associates an
  78. integer index with each link item. When the graph is built outgoing
  79. edges are sorted by this index.
  80. After the initial exploration of the link interface tree, any
  81. transitive (dependent) shared libraries that were encountered and not
  82. included in the interface are processed in their own BFS. This BFS
  83. follows only the dependent library lists and not the link interfaces.
  84. They are added to the link items with a mark indicating that the are
  85. transitive dependencies. Then cmComputeLinkInformation deals with
  86. them on a per-platform basis.
  87. The complete graph formed from all known and inferred dependencies may
  88. not be acyclic, so an acyclic version must be created.
  89. The original graph is converted to a directed acyclic graph in which
  90. each node corresponds to a strongly connected component of the
  91. original graph. For example, the dependency graph
  92. X -> A -> B -> C -> A -> Y
  93. contains strongly connected components {X}, {A,B,C}, and {Y}. The
  94. implied directed acyclic graph (DAG) is
  95. {X} -> {A,B,C} -> {Y}
  96. We then compute a topological order for the DAG nodes to serve as a
  97. reference for satisfying dependencies efficiently. We perform the DFS
  98. in reverse order and assign topological order indices counting down so
  99. that the result is as close to the original BFS order as possible
  100. without violating dependencies.
  101. ------------------------------------------------------------------------------
  102. The final link entry order is constructed as follows. We first walk
  103. through and emit the *original* link line as specified by the user.
  104. As each item is emitted, a set of pending nodes in the component DAG
  105. is maintained. When a pending component has been completely seen, it
  106. is removed from the pending set and its dependencies (following edges
  107. of the DAG) are added. A trivial component (those with one item) is
  108. complete as soon as its item is seen. A non-trivial component (one
  109. with more than one item; assumed to be static libraries) is complete
  110. when *all* its entries have been seen *twice* (all entries seen once,
  111. then all entries seen again, not just each entry twice). A pending
  112. component tracks which items have been seen and a count of how many
  113. times the component needs to be seen (once for trivial components,
  114. twice for non-trivial). If at any time another component finishes and
  115. re-adds an already pending component, the pending component is reset
  116. so that it needs to be seen in its entirety again. This ensures that
  117. all dependencies of a component are satisfied no matter where it
  118. appears.
  119. After the original link line has been completed, we append to it the
  120. remaining pending components and their dependencies. This is done by
  121. repeatedly emitting the first item from the first pending component
  122. and following the same update rules as when traversing the original
  123. link line. Since the pending components are kept in topological order
  124. they are emitted with minimal repeats (we do not want to emit a
  125. component just to have it added again when another component is
  126. completed later). This process continues until no pending components
  127. remain. We know it will terminate because the component graph is
  128. guaranteed to be acyclic.
  129. The final list of items produced by this procedure consists of the
  130. original user link line followed by minimal additional items needed to
  131. satisfy dependencies. The final list is then filtered to de-duplicate
  132. items that we know the linker will re-use automatically (shared libs).
  133. */
  134. cmComputeLinkDepends::cmComputeLinkDepends(const cmGeneratorTarget* target,
  135. const std::string& config)
  136. {
  137. // Store context information.
  138. this->Target = target;
  139. this->Makefile = this->Target->Target->GetMakefile();
  140. this->GlobalGenerator =
  141. this->Target->GetLocalGenerator()->GetGlobalGenerator();
  142. this->CMakeInstance = this->GlobalGenerator->GetCMakeInstance();
  143. // The configuration being linked.
  144. this->HasConfig = !config.empty();
  145. this->Config = (this->HasConfig) ? config : std::string();
  146. std::vector<std::string> debugConfigs =
  147. this->Makefile->GetCMakeInstance()->GetDebugConfigs();
  148. this->LinkType = CMP0003_ComputeLinkType(this->Config, debugConfigs);
  149. // Enable debug mode if requested.
  150. this->DebugMode = this->Makefile->IsOn("CMAKE_LINK_DEPENDS_DEBUG_MODE");
  151. // Assume no compatibility until set.
  152. this->OldLinkDirMode = false;
  153. // No computation has been done.
  154. this->CCG = nullptr;
  155. }
  156. cmComputeLinkDepends::~cmComputeLinkDepends()
  157. {
  158. cmDeleteAll(this->InferredDependSets);
  159. delete this->CCG;
  160. }
  161. void cmComputeLinkDepends::SetOldLinkDirMode(bool b)
  162. {
  163. this->OldLinkDirMode = b;
  164. }
  165. std::vector<cmComputeLinkDepends::LinkEntry> const&
  166. cmComputeLinkDepends::Compute()
  167. {
  168. // Follow the link dependencies of the target to be linked.
  169. this->AddDirectLinkEntries();
  170. // Complete the breadth-first search of dependencies.
  171. while (!this->BFSQueue.empty()) {
  172. // Get the next entry.
  173. BFSEntry qe = this->BFSQueue.front();
  174. this->BFSQueue.pop();
  175. // Follow the entry's dependencies.
  176. this->FollowLinkEntry(qe);
  177. }
  178. // Complete the search of shared library dependencies.
  179. while (!this->SharedDepQueue.empty()) {
  180. // Handle the next entry.
  181. this->HandleSharedDependency(this->SharedDepQueue.front());
  182. this->SharedDepQueue.pop();
  183. }
  184. // Infer dependencies of targets for which they were not known.
  185. this->InferDependencies();
  186. // Cleanup the constraint graph.
  187. this->CleanConstraintGraph();
  188. // Display the constraint graph.
  189. if (this->DebugMode) {
  190. fprintf(stderr, "---------------------------------------"
  191. "---------------------------------------\n");
  192. fprintf(stderr, "Link dependency analysis for target %s, config %s\n",
  193. this->Target->GetName().c_str(),
  194. this->HasConfig ? this->Config.c_str() : "noconfig");
  195. this->DisplayConstraintGraph();
  196. }
  197. // Compute the final ordering.
  198. this->OrderLinkEntires();
  199. // Compute the final set of link entries.
  200. // Iterate in reverse order so we can keep only the last occurrence
  201. // of a shared library.
  202. std::set<int> emmitted;
  203. for (std::vector<int>::const_reverse_iterator
  204. li = this->FinalLinkOrder.rbegin(),
  205. le = this->FinalLinkOrder.rend();
  206. li != le; ++li) {
  207. int i = *li;
  208. LinkEntry const& e = this->EntryList[i];
  209. cmGeneratorTarget const* t = e.Target;
  210. // Entries that we know the linker will re-use do not need to be repeated.
  211. bool uniquify = t && t->GetType() == cmStateEnums::SHARED_LIBRARY;
  212. if (!uniquify || emmitted.insert(i).second) {
  213. this->FinalLinkEntries.push_back(e);
  214. }
  215. }
  216. // Reverse the resulting order since we iterated in reverse.
  217. std::reverse(this->FinalLinkEntries.begin(), this->FinalLinkEntries.end());
  218. // Display the final set.
  219. if (this->DebugMode) {
  220. this->DisplayFinalEntries();
  221. }
  222. return this->FinalLinkEntries;
  223. }
  224. std::map<std::string, int>::iterator cmComputeLinkDepends::AllocateLinkEntry(
  225. std::string const& item)
  226. {
  227. std::map<std::string, int>::value_type index_entry(
  228. item, static_cast<int>(this->EntryList.size()));
  229. std::map<std::string, int>::iterator lei =
  230. this->LinkEntryIndex.insert(index_entry).first;
  231. this->EntryList.emplace_back();
  232. this->InferredDependSets.push_back(nullptr);
  233. this->EntryConstraintGraph.emplace_back();
  234. return lei;
  235. }
  236. int cmComputeLinkDepends::AddLinkEntry(cmLinkItem const& item)
  237. {
  238. // Check if the item entry has already been added.
  239. std::map<std::string, int>::iterator lei = this->LinkEntryIndex.find(item);
  240. if (lei != this->LinkEntryIndex.end()) {
  241. // Yes. We do not need to follow the item's dependencies again.
  242. return lei->second;
  243. }
  244. // Allocate a spot for the item entry.
  245. lei = this->AllocateLinkEntry(item);
  246. // Initialize the item entry.
  247. int index = lei->second;
  248. LinkEntry& entry = this->EntryList[index];
  249. entry.Item = item;
  250. entry.Target = item.Target;
  251. entry.IsFlag = (!entry.Target && item[0] == '-' && item[1] != 'l' &&
  252. item.substr(0, 10) != "-framework");
  253. // If the item has dependencies queue it to follow them.
  254. if (entry.Target) {
  255. // Target dependencies are always known. Follow them.
  256. BFSEntry qe = { index, nullptr };
  257. this->BFSQueue.push(qe);
  258. } else {
  259. // Look for an old-style <item>_LIB_DEPENDS variable.
  260. std::string var = entry.Item;
  261. var += "_LIB_DEPENDS";
  262. if (const char* val = this->Makefile->GetDefinition(var)) {
  263. // The item dependencies are known. Follow them.
  264. BFSEntry qe = { index, val };
  265. this->BFSQueue.push(qe);
  266. } else if (!entry.IsFlag) {
  267. // The item dependencies are not known. We need to infer them.
  268. this->InferredDependSets[index] = new DependSetList;
  269. }
  270. }
  271. return index;
  272. }
  273. void cmComputeLinkDepends::FollowLinkEntry(BFSEntry qe)
  274. {
  275. // Get this entry representation.
  276. int depender_index = qe.Index;
  277. LinkEntry const& entry = this->EntryList[depender_index];
  278. // Follow the item's dependencies.
  279. if (entry.Target) {
  280. // Follow the target dependencies.
  281. if (cmLinkInterface const* iface =
  282. entry.Target->GetLinkInterface(this->Config, this->Target)) {
  283. const bool isIface =
  284. entry.Target->GetType() == cmStateEnums::INTERFACE_LIBRARY;
  285. // This target provides its own link interface information.
  286. this->AddLinkEntries(depender_index, iface->Libraries);
  287. if (isIface) {
  288. return;
  289. }
  290. // Handle dependent shared libraries.
  291. this->FollowSharedDeps(depender_index, iface);
  292. // Support for CMP0003.
  293. for (cmLinkItem const& oi : iface->WrongConfigLibraries) {
  294. this->CheckWrongConfigItem(oi);
  295. }
  296. }
  297. } else {
  298. // Follow the old-style dependency list.
  299. this->AddVarLinkEntries(depender_index, qe.LibDepends);
  300. }
  301. }
  302. void cmComputeLinkDepends::FollowSharedDeps(int depender_index,
  303. cmLinkInterface const* iface,
  304. bool follow_interface)
  305. {
  306. // Follow dependencies if we have not followed them already.
  307. if (this->SharedDepFollowed.insert(depender_index).second) {
  308. if (follow_interface) {
  309. this->QueueSharedDependencies(depender_index, iface->Libraries);
  310. }
  311. this->QueueSharedDependencies(depender_index, iface->SharedDeps);
  312. }
  313. }
  314. void cmComputeLinkDepends::QueueSharedDependencies(
  315. int depender_index, std::vector<cmLinkItem> const& deps)
  316. {
  317. for (cmLinkItem const& li : deps) {
  318. SharedDepEntry qe;
  319. qe.Item = li;
  320. qe.DependerIndex = depender_index;
  321. this->SharedDepQueue.push(qe);
  322. }
  323. }
  324. void cmComputeLinkDepends::HandleSharedDependency(SharedDepEntry const& dep)
  325. {
  326. // Check if the target already has an entry.
  327. std::map<std::string, int>::iterator lei =
  328. this->LinkEntryIndex.find(dep.Item);
  329. if (lei == this->LinkEntryIndex.end()) {
  330. // Allocate a spot for the item entry.
  331. lei = this->AllocateLinkEntry(dep.Item);
  332. // Initialize the item entry.
  333. LinkEntry& entry = this->EntryList[lei->second];
  334. entry.Item = dep.Item;
  335. entry.Target = dep.Item.Target;
  336. // This item was added specifically because it is a dependent
  337. // shared library. It may get special treatment
  338. // in cmComputeLinkInformation.
  339. entry.IsSharedDep = true;
  340. }
  341. // Get the link entry for this target.
  342. int index = lei->second;
  343. LinkEntry& entry = this->EntryList[index];
  344. // This shared library dependency must follow the item that listed
  345. // it.
  346. this->EntryConstraintGraph[dep.DependerIndex].push_back(index);
  347. // Target items may have their own dependencies.
  348. if (entry.Target) {
  349. if (cmLinkInterface const* iface =
  350. entry.Target->GetLinkInterface(this->Config, this->Target)) {
  351. // Follow public and private dependencies transitively.
  352. this->FollowSharedDeps(index, iface, true);
  353. }
  354. }
  355. }
  356. void cmComputeLinkDepends::AddVarLinkEntries(int depender_index,
  357. const char* value)
  358. {
  359. // This is called to add the dependencies named by
  360. // <item>_LIB_DEPENDS. The variable contains a semicolon-separated
  361. // list. The list contains link-type;item pairs and just items.
  362. std::vector<std::string> deplist;
  363. cmSystemTools::ExpandListArgument(value, deplist);
  364. // Look for entries meant for this configuration.
  365. std::vector<cmLinkItem> actual_libs;
  366. cmTargetLinkLibraryType llt = GENERAL_LibraryType;
  367. bool haveLLT = false;
  368. for (std::string const& d : deplist) {
  369. if (d == "debug") {
  370. llt = DEBUG_LibraryType;
  371. haveLLT = true;
  372. } else if (d == "optimized") {
  373. llt = OPTIMIZED_LibraryType;
  374. haveLLT = true;
  375. } else if (d == "general") {
  376. llt = GENERAL_LibraryType;
  377. haveLLT = true;
  378. } else if (!d.empty()) {
  379. // If no explicit link type was given prior to this entry then
  380. // check if the entry has its own link type variable. This is
  381. // needed for compatibility with dependency files generated by
  382. // the export_library_dependencies command from CMake 2.4 and
  383. // lower.
  384. if (!haveLLT) {
  385. std::string var = d;
  386. var += "_LINK_TYPE";
  387. if (const char* val = this->Makefile->GetDefinition(var)) {
  388. if (strcmp(val, "debug") == 0) {
  389. llt = DEBUG_LibraryType;
  390. } else if (strcmp(val, "optimized") == 0) {
  391. llt = OPTIMIZED_LibraryType;
  392. }
  393. }
  394. }
  395. // If the library is meant for this link type then use it.
  396. if (llt == GENERAL_LibraryType || llt == this->LinkType) {
  397. actual_libs.emplace_back(d, this->FindTargetToLink(depender_index, d));
  398. } else if (this->OldLinkDirMode) {
  399. cmLinkItem item(d, this->FindTargetToLink(depender_index, d));
  400. this->CheckWrongConfigItem(item);
  401. }
  402. // Reset the link type until another explicit type is given.
  403. llt = GENERAL_LibraryType;
  404. haveLLT = false;
  405. }
  406. }
  407. // Add the entries from this list.
  408. this->AddLinkEntries(depender_index, actual_libs);
  409. }
  410. void cmComputeLinkDepends::AddDirectLinkEntries()
  411. {
  412. // Add direct link dependencies in this configuration.
  413. cmLinkImplementation const* impl =
  414. this->Target->GetLinkImplementation(this->Config);
  415. this->AddLinkEntries(-1, impl->Libraries);
  416. for (cmLinkItem const& wi : impl->WrongConfigLibraries) {
  417. this->CheckWrongConfigItem(wi);
  418. }
  419. }
  420. template <typename T>
  421. void cmComputeLinkDepends::AddLinkEntries(int depender_index,
  422. std::vector<T> const& libs)
  423. {
  424. // Track inferred dependency sets implied by this list.
  425. std::map<int, DependSet> dependSets;
  426. // Loop over the libraries linked directly by the depender.
  427. for (T const& l : libs) {
  428. // Skip entries that will resolve to the target getting linked or
  429. // are empty.
  430. cmLinkItem const& item = l;
  431. if (item == this->Target->GetName() || item.empty()) {
  432. continue;
  433. }
  434. // Add a link entry for this item.
  435. int dependee_index = this->AddLinkEntry(l);
  436. // The dependee must come after the depender.
  437. if (depender_index >= 0) {
  438. this->EntryConstraintGraph[depender_index].push_back(dependee_index);
  439. } else {
  440. // This is a direct dependency of the target being linked.
  441. this->OriginalEntries.push_back(dependee_index);
  442. }
  443. // Update the inferred dependencies for earlier items.
  444. for (auto& dependSet : dependSets) {
  445. // Add this item to the inferred dependencies of other items.
  446. // Target items are never inferred dependees because unknown
  447. // items are outside libraries that should not be depending on
  448. // targets.
  449. if (!this->EntryList[dependee_index].Target &&
  450. !this->EntryList[dependee_index].IsFlag &&
  451. dependee_index != dependSet.first) {
  452. dependSet.second.insert(dependee_index);
  453. }
  454. }
  455. // If this item needs to have dependencies inferred, do so.
  456. if (this->InferredDependSets[dependee_index]) {
  457. // Make sure an entry exists to hold the set for the item.
  458. dependSets[dependee_index];
  459. }
  460. }
  461. // Store the inferred dependency sets discovered for this list.
  462. for (auto const& dependSet : dependSets) {
  463. this->InferredDependSets[dependSet.first]->push_back(dependSet.second);
  464. }
  465. }
  466. cmGeneratorTarget const* cmComputeLinkDepends::FindTargetToLink(
  467. int depender_index, const std::string& name)
  468. {
  469. // Look for a target in the scope of the depender.
  470. cmGeneratorTarget const* from = this->Target;
  471. if (depender_index >= 0) {
  472. if (cmGeneratorTarget const* depender =
  473. this->EntryList[depender_index].Target) {
  474. from = depender;
  475. }
  476. }
  477. return from->FindTargetToLink(name);
  478. }
  479. void cmComputeLinkDepends::InferDependencies()
  480. {
  481. // The inferred dependency sets for each item list the possible
  482. // dependencies. The intersection of the sets for one item form its
  483. // inferred dependencies.
  484. for (unsigned int depender_index = 0;
  485. depender_index < this->InferredDependSets.size(); ++depender_index) {
  486. // Skip items for which dependencies do not need to be inferred or
  487. // for which the inferred dependency sets are empty.
  488. DependSetList* sets = this->InferredDependSets[depender_index];
  489. if (!sets || sets->empty()) {
  490. continue;
  491. }
  492. // Intersect the sets for this item.
  493. DependSetList::const_iterator i = sets->begin();
  494. DependSet common = *i;
  495. for (++i; i != sets->end(); ++i) {
  496. DependSet intersection;
  497. std::set_intersection(common.begin(), common.end(), i->begin(), i->end(),
  498. std::inserter(intersection, intersection.begin()));
  499. common = intersection;
  500. }
  501. // Add the inferred dependencies to the graph.
  502. cmGraphEdgeList& edges = this->EntryConstraintGraph[depender_index];
  503. edges.insert(edges.end(), common.begin(), common.end());
  504. }
  505. }
  506. void cmComputeLinkDepends::CleanConstraintGraph()
  507. {
  508. for (cmGraphEdgeList& edgeList : this->EntryConstraintGraph) {
  509. // Sort the outgoing edges for each graph node so that the
  510. // original order will be preserved as much as possible.
  511. std::sort(edgeList.begin(), edgeList.end());
  512. // Make the edge list unique.
  513. edgeList.erase(std::unique(edgeList.begin(), edgeList.end()),
  514. edgeList.end());
  515. }
  516. }
  517. void cmComputeLinkDepends::DisplayConstraintGraph()
  518. {
  519. // Display the graph nodes and their edges.
  520. std::ostringstream e;
  521. for (unsigned int i = 0; i < this->EntryConstraintGraph.size(); ++i) {
  522. EdgeList const& nl = this->EntryConstraintGraph[i];
  523. e << "item " << i << " is [" << this->EntryList[i].Item << "]\n";
  524. e << cmWrap(" item ", nl, " must follow it", "\n") << "\n";
  525. }
  526. fprintf(stderr, "%s\n", e.str().c_str());
  527. }
  528. void cmComputeLinkDepends::OrderLinkEntires()
  529. {
  530. // Compute the DAG of strongly connected components. The algorithm
  531. // used by cmComputeComponentGraph should identify the components in
  532. // the same order in which the items were originally discovered in
  533. // the BFS. This should preserve the original order when no
  534. // constraints disallow it.
  535. this->CCG = new cmComputeComponentGraph(this->EntryConstraintGraph);
  536. // The component graph is guaranteed to be acyclic. Start a DFS
  537. // from every entry to compute a topological order for the
  538. // components.
  539. Graph const& cgraph = this->CCG->GetComponentGraph();
  540. int n = static_cast<int>(cgraph.size());
  541. this->ComponentVisited.resize(cgraph.size(), 0);
  542. this->ComponentOrder.resize(cgraph.size(), n);
  543. this->ComponentOrderId = n;
  544. // Run in reverse order so the topological order will preserve the
  545. // original order where there are no constraints.
  546. for (int c = n - 1; c >= 0; --c) {
  547. this->VisitComponent(c);
  548. }
  549. // Display the component graph.
  550. if (this->DebugMode) {
  551. this->DisplayComponents();
  552. }
  553. // Start with the original link line.
  554. for (int originalEntry : this->OriginalEntries) {
  555. this->VisitEntry(originalEntry);
  556. }
  557. // Now explore anything left pending. Since the component graph is
  558. // guaranteed to be acyclic we know this will terminate.
  559. while (!this->PendingComponents.empty()) {
  560. // Visit one entry from the first pending component. The visit
  561. // logic will update the pending components accordingly. Since
  562. // the pending components are kept in topological order this will
  563. // not repeat one.
  564. int e = *this->PendingComponents.begin()->second.Entries.begin();
  565. this->VisitEntry(e);
  566. }
  567. }
  568. void cmComputeLinkDepends::DisplayComponents()
  569. {
  570. fprintf(stderr, "The strongly connected components are:\n");
  571. std::vector<NodeList> const& components = this->CCG->GetComponents();
  572. for (unsigned int c = 0; c < components.size(); ++c) {
  573. fprintf(stderr, "Component (%u):\n", c);
  574. NodeList const& nl = components[c];
  575. for (int i : nl) {
  576. fprintf(stderr, " item %d [%s]\n", i, this->EntryList[i].Item.c_str());
  577. }
  578. EdgeList const& ol = this->CCG->GetComponentGraphEdges(c);
  579. for (cmGraphEdge const& oi : ol) {
  580. int i = oi;
  581. fprintf(stderr, " followed by Component (%d)\n", i);
  582. }
  583. fprintf(stderr, " topo order index %d\n", this->ComponentOrder[c]);
  584. }
  585. fprintf(stderr, "\n");
  586. }
  587. void cmComputeLinkDepends::VisitComponent(unsigned int c)
  588. {
  589. // Check if the node has already been visited.
  590. if (this->ComponentVisited[c]) {
  591. return;
  592. }
  593. // We are now visiting this component so mark it.
  594. this->ComponentVisited[c] = 1;
  595. // Visit the neighbors of the component first.
  596. // Run in reverse order so the topological order will preserve the
  597. // original order where there are no constraints.
  598. EdgeList const& nl = this->CCG->GetComponentGraphEdges(c);
  599. for (EdgeList::const_reverse_iterator ni = nl.rbegin(); ni != nl.rend();
  600. ++ni) {
  601. this->VisitComponent(*ni);
  602. }
  603. // Assign an ordering id to this component.
  604. this->ComponentOrder[c] = --this->ComponentOrderId;
  605. }
  606. void cmComputeLinkDepends::VisitEntry(int index)
  607. {
  608. // Include this entry on the link line.
  609. this->FinalLinkOrder.push_back(index);
  610. // This entry has now been seen. Update its component.
  611. bool completed = false;
  612. int component = this->CCG->GetComponentMap()[index];
  613. std::map<int, PendingComponent>::iterator mi =
  614. this->PendingComponents.find(this->ComponentOrder[component]);
  615. if (mi != this->PendingComponents.end()) {
  616. // The entry is in an already pending component.
  617. PendingComponent& pc = mi->second;
  618. // Remove the entry from those pending in its component.
  619. pc.Entries.erase(index);
  620. if (pc.Entries.empty()) {
  621. // The complete component has been seen since it was last needed.
  622. --pc.Count;
  623. if (pc.Count == 0) {
  624. // The component has been completed.
  625. this->PendingComponents.erase(mi);
  626. completed = true;
  627. } else {
  628. // The whole component needs to be seen again.
  629. NodeList const& nl = this->CCG->GetComponent(component);
  630. assert(nl.size() > 1);
  631. pc.Entries.insert(nl.begin(), nl.end());
  632. }
  633. }
  634. } else {
  635. // The entry is not in an already pending component.
  636. NodeList const& nl = this->CCG->GetComponent(component);
  637. if (nl.size() > 1) {
  638. // This is a non-trivial component. It is now pending.
  639. PendingComponent& pc = this->MakePendingComponent(component);
  640. // The starting entry has already been seen.
  641. pc.Entries.erase(index);
  642. } else {
  643. // This is a trivial component, so it is already complete.
  644. completed = true;
  645. }
  646. }
  647. // If the entry completed a component, the component's dependencies
  648. // are now pending.
  649. if (completed) {
  650. EdgeList const& ol = this->CCG->GetComponentGraphEdges(component);
  651. for (cmGraphEdge const& oi : ol) {
  652. // This entire component is now pending no matter whether it has
  653. // been partially seen already.
  654. this->MakePendingComponent(oi);
  655. }
  656. }
  657. }
  658. cmComputeLinkDepends::PendingComponent&
  659. cmComputeLinkDepends::MakePendingComponent(unsigned int component)
  660. {
  661. // Create an entry (in topological order) for the component.
  662. PendingComponent& pc =
  663. this->PendingComponents[this->ComponentOrder[component]];
  664. pc.Id = component;
  665. NodeList const& nl = this->CCG->GetComponent(component);
  666. if (nl.size() == 1) {
  667. // Trivial components need be seen only once.
  668. pc.Count = 1;
  669. } else {
  670. // This is a non-trivial strongly connected component of the
  671. // original graph. It consists of two or more libraries
  672. // (archives) that mutually require objects from one another. In
  673. // the worst case we may have to repeat the list of libraries as
  674. // many times as there are object files in the biggest archive.
  675. // For now we just list them twice.
  676. //
  677. // The list of items in the component has been sorted by the order
  678. // of discovery in the original BFS of dependencies. This has the
  679. // advantage that the item directly linked by a target requiring
  680. // this component will come first which minimizes the number of
  681. // repeats needed.
  682. pc.Count = this->ComputeComponentCount(nl);
  683. }
  684. // Store the entries to be seen.
  685. pc.Entries.insert(nl.begin(), nl.end());
  686. return pc;
  687. }
  688. int cmComputeLinkDepends::ComputeComponentCount(NodeList const& nl)
  689. {
  690. unsigned int count = 2;
  691. for (int ni : nl) {
  692. if (cmGeneratorTarget const* target = this->EntryList[ni].Target) {
  693. if (cmLinkInterface const* iface =
  694. target->GetLinkInterface(this->Config, this->Target)) {
  695. if (iface->Multiplicity > count) {
  696. count = iface->Multiplicity;
  697. }
  698. }
  699. }
  700. }
  701. return count;
  702. }
  703. void cmComputeLinkDepends::DisplayFinalEntries()
  704. {
  705. fprintf(stderr, "target [%s] links to:\n", this->Target->GetName().c_str());
  706. for (LinkEntry const& lei : this->FinalLinkEntries) {
  707. if (lei.Target) {
  708. fprintf(stderr, " target [%s]\n", lei.Target->GetName().c_str());
  709. } else {
  710. fprintf(stderr, " item [%s]\n", lei.Item.c_str());
  711. }
  712. }
  713. fprintf(stderr, "\n");
  714. }
  715. void cmComputeLinkDepends::CheckWrongConfigItem(cmLinkItem const& item)
  716. {
  717. if (!this->OldLinkDirMode) {
  718. return;
  719. }
  720. // For CMake 2.4 bug-compatibility we need to consider the output
  721. // directories of targets linked in another configuration as link
  722. // directories.
  723. if (item.Target && !item.Target->IsImported()) {
  724. this->OldWrongConfigItems.insert(item.Target);
  725. }
  726. }