Coverage Report

Created: 2026-10-28 06:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Source/cmComputeLinkDepends.cxx
Line
Count
Source
1
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2
   file LICENSE.rst or https://cmake.org/licensing for details.  */
3
#include "cmComputeLinkDepends.h"
4
5
#include <algorithm>
6
#include <cassert>
7
#include <cstddef>
8
#include <cstdio>
9
#include <iterator>
10
#include <sstream>
11
#include <unordered_map>
12
#include <utility>
13
14
#include <cm/memory>
15
#include <cm/string_view>
16
#include <cmext/string_view>
17
18
#include "cmsys/RegularExpression.hxx"
19
20
#include "cmComputeComponentGraph.h"
21
#include "cmDiagnostics.h"
22
#include "cmGenExContext.h"
23
#include "cmGeneratorExpression.h"
24
#include "cmGeneratorExpressionDAGChecker.h"
25
#include "cmGeneratorTarget.h"
26
#include "cmGlobalGenerator.h"
27
#include "cmList.h"
28
#include "cmListFileCache.h"
29
#include "cmLocalGenerator.h"
30
#include "cmMakefile.h"
31
#include "cmMessageType.h"
32
#include "cmPolicies.h"
33
#include "cmRange.h"
34
#include "cmState.h"
35
#include "cmStringAlgorithms.h"
36
#include "cmTarget.h"
37
#include "cmTargetTypes.h"
38
#include "cmValue.h"
39
#include "cmake.h"
40
41
/*
42
43
This file computes an ordered list of link items to use when linking a
44
single target in one configuration.  Each link item is identified by
45
the string naming it.  A graph of dependencies is created in which
46
each node corresponds to one item and directed edges lead from nodes to
47
those which must *follow* them on the link line.  For example, the
48
graph
49
50
  A -> B -> C
51
52
will lead to the link line order
53
54
  A B C
55
56
The set of items placed in the graph is formed with a breadth-first
57
search of the link dependencies starting from the main target.
58
59
There are two types of items: those with known direct dependencies and
60
those without known dependencies.  We will call the two types "known
61
items" and "unknown items", respectively.  Known items are those whose
62
names correspond to targets (built or imported) and those for which an
63
old-style <item>_LIB_DEPENDS variable is defined.  All other items are
64
unknown and we must infer dependencies for them.  For items that look
65
like flags (beginning with '-') we trivially infer no dependencies,
66
and do not include them in the dependencies of other items.
67
68
Known items have dependency lists ordered based on how the user
69
specified them.  We can use this order to infer potential dependencies
70
of unknown items.  For example, if link items A and B are unknown and
71
items X and Y are known, then we might have the following dependency
72
lists:
73
74
  X: Y A B
75
  Y: A B
76
77
The explicitly known dependencies form graph edges
78
79
  X -> Y  ,  X -> A  ,  X -> B  ,  Y -> A  ,  Y -> B
80
81
We can also infer the edge
82
83
  A -> B
84
85
because *every* time A appears B is seen on its right.  We do not know
86
whether A really needs symbols from B to link, but it *might* so we
87
must preserve their order.  This is the case also for the following
88
explicit lists:
89
90
  X: A B Y
91
  Y: A B
92
93
Here, A is followed by the set {B,Y} in one list, and {B} in the other
94
list.  The intersection of these sets is {B}, so we can infer that A
95
depends on at most B.  Meanwhile B is followed by the set {Y} in one
96
list and {} in the other.  The intersection is {} so we can infer that
97
B has no dependencies.
98
99
Let's make a more complex example by adding unknown item C and
100
considering these dependency lists:
101
102
  X: A B Y C
103
  Y: A C B
104
105
The explicit edges are
106
107
  X -> Y  ,  X -> A  ,  X -> B  ,  X -> C  ,  Y -> A  ,  Y -> B  ,  Y -> C
108
109
For the unknown items, we infer dependencies by looking at the
110
"follow" sets:
111
112
  A: intersect( {B,Y,C} , {C,B} ) = {B,C} ; infer edges  A -> B  ,  A -> C
113
  B: intersect( {Y,C}   , {}    ) = {}    ; infer no edges
114
  C: intersect( {}      , {B}   ) = {}    ; infer no edges
115
116
Note that targets are never inferred as dependees because outside
117
libraries should not depend on them.
118
119
------------------------------------------------------------------------------
120
121
The initial exploration of dependencies using a BFS associates an
122
integer index with each link item.  When the graph is built outgoing
123
edges are sorted by this index.
124
125
After the initial exploration of the link interface tree, any
126
transitive (dependent) shared libraries that were encountered and not
127
included in the interface are processed in their own BFS.  This BFS
128
follows only the dependent library lists and not the link interfaces.
129
They are added to the link items with a mark indicating that the are
130
transitive dependencies.  Then cmComputeLinkInformation deals with
131
them on a per-platform basis.
132
133
The complete graph formed from all known and inferred dependencies may
134
not be acyclic, so an acyclic version must be created.
135
The original graph is converted to a directed acyclic graph in which
136
each node corresponds to a strongly connected component of the
137
original graph.  For example, the dependency graph
138
139
  X -> A -> B -> C -> A -> Y
140
141
contains strongly connected components {X}, {A,B,C}, and {Y}.  The
142
implied directed acyclic graph (DAG) is
143
144
  {X} -> {A,B,C} -> {Y}
145
146
We then compute a topological order for the DAG nodes to serve as a
147
reference for satisfying dependencies efficiently.  We perform the DFS
148
in reverse order and assign topological order indices counting down so
149
that the result is as close to the original BFS order as possible
150
without violating dependencies.
151
152
------------------------------------------------------------------------------
153
154
The final link entry order is constructed as follows.  We first walk
155
through and emit the *original* link line as specified by the user.
156
As each item is emitted, a set of pending nodes in the component DAG
157
is maintained.  When a pending component has been completely seen, it
158
is removed from the pending set and its dependencies (following edges
159
of the DAG) are added.  A trivial component (those with one item) is
160
complete as soon as its item is seen.  A non-trivial component (one
161
with more than one item; assumed to be static libraries) is complete
162
when *all* its entries have been seen *twice* (all entries seen once,
163
then all entries seen again, not just each entry twice).  A pending
164
component tracks which items have been seen and a count of how many
165
times the component needs to be seen (once for trivial components,
166
twice for non-trivial).  If at any time another component finishes and
167
re-adds an already pending component, the pending component is reset
168
so that it needs to be seen in its entirety again.  This ensures that
169
all dependencies of a component are satisfied no matter where it
170
appears.
171
172
After the original link line has been completed, we append to it the
173
remaining pending components and their dependencies.  This is done by
174
repeatedly emitting the first item from the first pending component
175
and following the same update rules as when traversing the original
176
link line.  Since the pending components are kept in topological order
177
they are emitted with minimal repeats (we do not want to emit a
178
component just to have it added again when another component is
179
completed later).  This process continues until no pending components
180
remain.  We know it will terminate because the component graph is
181
guaranteed to be acyclic.
182
183
The final list of items produced by this procedure consists of the
184
original user link line followed by minimal additional items needed to
185
satisfy dependencies.  The final list is then filtered to de-duplicate
186
items that we know the linker will reuse automatically (shared libs).
187
188
*/
189
190
namespace {
191
// LINK_LIBRARY helpers
192
bool IsFeatureSupported(cmMakefile* makefile, std::string const& linkLanguage,
193
                        std::string const& feature)
194
0
{
195
0
  auto featureSupported = cmStrCat(
196
0
    "CMAKE_", linkLanguage, "_LINK_LIBRARY_USING_", feature, "_SUPPORTED");
197
0
  if (cmValue perLangVar = makefile->GetDefinition(featureSupported)) {
198
0
    return perLangVar.IsOn();
199
0
  }
200
201
0
  featureSupported =
202
0
    cmStrCat("CMAKE_LINK_LIBRARY_USING_", feature, "_SUPPORTED");
203
0
  return makefile->GetDefinition(featureSupported).IsOn();
204
0
}
205
206
// LINK_LIBRARY feature attributes management
207
struct LinkLibraryFeatureAttributeSet
208
{
209
  std::set<cm::TargetType> LibraryTypes = { cm::TargetType::EXECUTABLE,
210
                                            cm::TargetType::STATIC_LIBRARY,
211
                                            cm::TargetType::SHARED_LIBRARY,
212
                                            cm::TargetType::MODULE_LIBRARY,
213
                                            cm::TargetType::UNKNOWN_LIBRARY };
214
  std::set<std::string> Override;
215
216
  enum DeduplicationKind
217
  {
218
    Default,
219
    Yes,
220
    No
221
  };
222
  DeduplicationKind Deduplication = Default;
223
};
224
std::map<std::string, LinkLibraryFeatureAttributeSet>
225
  LinkLibraryFeatureAttributes;
226
LinkLibraryFeatureAttributeSet const& GetLinkLibraryFeatureAttributes(
227
  cmMakefile* makefile, std::string const& linkLanguage,
228
  std::string const& feature)
229
0
{
230
0
  auto it = LinkLibraryFeatureAttributes.find(feature);
231
0
  if (it != LinkLibraryFeatureAttributes.end()) {
232
0
    return it->second;
233
0
  }
234
235
0
  auto featureAttributesVariable =
236
0
    cmStrCat("CMAKE_", linkLanguage, "_LINK_LIBRARY_", feature, "_ATTRIBUTES");
237
0
  auto featureAttributesValues =
238
0
    makefile->GetDefinition(featureAttributesVariable);
239
0
  if (featureAttributesValues.IsEmpty()) {
240
    // try language agnostic definition
241
0
    featureAttributesVariable =
242
0
      cmStrCat("CMAKE_LINK_LIBRARY_", feature, "_ATTRIBUTES");
243
0
    featureAttributesValues =
244
0
      makefile->GetDefinition(featureAttributesVariable);
245
0
  }
246
0
  if (!featureAttributesValues.IsEmpty()) {
247
0
    LinkLibraryFeatureAttributeSet featureAttributes;
248
0
    cmsys::RegularExpression processingOption{
249
0
      "^(LIBRARY_TYPE|DEDUPLICATION|OVERRIDE)=((STATIC|SHARED|MODULE|"
250
0
      "EXECUTABLE)(,("
251
0
      "STATIC|"
252
0
      "SHARED|MODULE|EXECUTABLE)"
253
0
      ")*|YES|NO|DEFAULT|[A-Za-z0-9_]+(,[A-Za-z0-9_]+)*)$"
254
0
    };
255
0
    std::string errorMessage;
256
0
    for (auto const& option : cmList{ featureAttributesValues }) {
257
0
      if (processingOption.find(option)) {
258
0
        if (processingOption.match(1) == "LIBRARY_TYPE") {
259
0
          featureAttributes.LibraryTypes.clear();
260
0
          for (auto const& value :
261
0
               cmTokenize(processingOption.match(2), ',')) {
262
0
            if (value == "STATIC") {
263
0
              featureAttributes.LibraryTypes.emplace(
264
0
                cm::TargetType::STATIC_LIBRARY);
265
0
            } else if (value == "SHARED") {
266
0
              featureAttributes.LibraryTypes.emplace(
267
0
                cm::TargetType::SHARED_LIBRARY);
268
0
            } else if (value == "MODULE") {
269
0
              featureAttributes.LibraryTypes.emplace(
270
0
                cm::TargetType::MODULE_LIBRARY);
271
0
            } else if (value == "EXECUTABLE") {
272
0
              featureAttributes.LibraryTypes.emplace(
273
0
                cm::TargetType::EXECUTABLE);
274
0
            } else {
275
0
              errorMessage =
276
0
                cmStrCat(std::move(errorMessage), "  ", option, '\n');
277
0
              break;
278
0
            }
279
0
          }
280
          // Always add UNKNOWN type
281
0
          featureAttributes.LibraryTypes.emplace(
282
0
            cm::TargetType::UNKNOWN_LIBRARY);
283
0
        } else if (processingOption.match(1) == "DEDUPLICATION") {
284
0
          if (processingOption.match(2) == "YES") {
285
0
            featureAttributes.Deduplication =
286
0
              LinkLibraryFeatureAttributeSet::Yes;
287
0
          } else if (processingOption.match(2) == "NO") {
288
0
            featureAttributes.Deduplication =
289
0
              LinkLibraryFeatureAttributeSet::No;
290
0
          } else if (processingOption.match(2) == "DEFAULT") {
291
0
            featureAttributes.Deduplication =
292
0
              LinkLibraryFeatureAttributeSet::Default;
293
0
          } else {
294
0
            errorMessage =
295
0
              cmStrCat(std::move(errorMessage), "  ", option, '\n');
296
0
          }
297
0
        } else if (processingOption.match(1) == "OVERRIDE") {
298
0
          featureAttributes.Override.clear();
299
0
          std::vector<std::string> values =
300
0
            cmTokenize(processingOption.match(2), ',');
301
0
          featureAttributes.Override.insert(values.begin(), values.end());
302
0
        }
303
0
      } else {
304
0
        errorMessage = cmStrCat(std::move(errorMessage), "  ", option, '\n');
305
0
      }
306
0
    }
307
0
    if (!errorMessage.empty()) {
308
0
      makefile->GetCMakeInstance()->IssueMessage(
309
0
        MessageType::FATAL_ERROR,
310
0
        cmStrCat("Erroneous option(s) for '", featureAttributesVariable,
311
0
                 "':\n", errorMessage));
312
0
    }
313
0
    return LinkLibraryFeatureAttributes.emplace(feature, featureAttributes)
314
0
      .first->second;
315
0
  }
316
0
  return LinkLibraryFeatureAttributes
317
0
    .emplace(feature, LinkLibraryFeatureAttributeSet{})
318
0
    .first->second;
319
0
}
320
321
// LINK_GROUP helpers
322
cm::string_view const LG_BEGIN = "<LINK_GROUP:"_s;
323
cm::string_view const LG_END = "</LINK_GROUP:"_s;
324
cm::string_view const LG_ITEM_BEGIN = "<LINK_GROUP>"_s;
325
cm::string_view const LG_ITEM_END = "</LINK_GROUP>"_s;
326
327
inline std::string ExtractGroupFeature(std::string const& item)
328
0
{
329
0
  return item.substr(LG_BEGIN.length(),
330
0
                     item.find(':', LG_BEGIN.length()) - LG_BEGIN.length());
331
0
}
332
333
bool IsGroupFeatureSupported(cmMakefile* makefile,
334
                             std::string const& linkLanguage,
335
                             std::string const& feature)
336
0
{
337
0
  auto featureSupported = cmStrCat(
338
0
    "CMAKE_", linkLanguage, "_LINK_GROUP_USING_", feature, "_SUPPORTED");
339
0
  if (makefile->GetDefinition(featureSupported).IsOn()) {
340
0
    return true;
341
0
  }
342
343
0
  featureSupported =
344
0
    cmStrCat("CMAKE_LINK_GROUP_USING_", feature, "_SUPPORTED");
345
0
  return makefile->GetDefinition(featureSupported).IsOn();
346
0
}
347
348
class EntriesProcessing
349
{
350
public:
351
  using LinkEntry = cmComputeLinkDepends::LinkEntry;
352
  using EntryVector = cmComputeLinkDepends::EntryVector;
353
354
  EntriesProcessing(cmGeneratorTarget const* target,
355
                    std::string const& linkLanguage, EntryVector& entries,
356
                    EntryVector& finalEntries)
357
0
    : Target(target)
358
0
    , LinkLanguage(linkLanguage)
359
0
    , Entries(entries)
360
0
    , FinalEntries(finalEntries)
361
0
  {
362
0
    auto const* makefile = target->Makefile;
363
364
0
    switch (target->GetPolicyStatusCMP0156()) {
365
0
      case cmPolicies::WARN:
366
0
        if (!makefile->GetCMakeInstance()->GetIsInTryCompile() &&
367
0
            makefile->PolicyOptionalWarningEnabled(
368
0
              "CMAKE_POLICY_WARNING_CMP0156")) {
369
0
          makefile->IssuePolicyWarning(
370
0
            cmPolicies::CMP0156, {},
371
0
            "Since the policy is not set, legacy libraries "
372
0
            "de-duplication strategy will be applied."_s,
373
0
            target->GetBacktrace());
374
0
        }
375
0
        CM_FALLTHROUGH;
376
0
      case cmPolicies::OLD:
377
        // rely on default initialization of the class
378
0
        break;
379
0
      case cmPolicies::NEW: {
380
        // Policy 0179 applies only when policy 0156 is new
381
0
        if (target->GetPolicyStatusCMP0179() == cmPolicies::WARN &&
382
0
            !makefile->GetCMakeInstance()->GetIsInTryCompile() &&
383
0
            makefile->PolicyOptionalWarningEnabled(
384
0
              "CMAKE_POLICY_WARNING_CMP0179")) {
385
0
          makefile->IssuePolicyWarning(
386
0
            cmPolicies::CMP0179, {},
387
0
            "Since the policy is not set, static libraries de-duplication "
388
0
            "will keep the last occurrence of the static libraries."_s,
389
0
            target->GetBacktrace());
390
0
        }
391
392
0
        if (auto libProcessing = makefile->GetDefinition(cmStrCat(
393
0
              "CMAKE_", linkLanguage, "_LINK_LIBRARIES_PROCESSING"))) {
394
          // UNICITY keyword is just for compatibility with previous
395
          // implementation
396
0
          cmsys::RegularExpression processingOption{
397
0
            "^(ORDER|UNICITY|DEDUPLICATION)=(FORWARD|REVERSE|ALL|NONE|SHARED)$"
398
0
          };
399
0
          std::string errorMessage;
400
0
          for (auto const& option : cmList{ libProcessing }) {
401
0
            if (processingOption.find(option)) {
402
0
              if (processingOption.match(1) == "ORDER") {
403
0
                if (processingOption.match(2) == "FORWARD") {
404
0
                  this->Order = Forward;
405
0
                } else if (processingOption.match(2) == "REVERSE") {
406
0
                  this->Order = Reverse;
407
0
                } else {
408
0
                  errorMessage =
409
0
                    cmStrCat(std::move(errorMessage), "  ", option, '\n');
410
0
                }
411
0
              } else if (processingOption.match(1) == "UNICITY" ||
412
0
                         processingOption.match(1) == "DEDUPLICATION") {
413
0
                if (processingOption.match(2) == "ALL") {
414
0
                  this->Deduplication = All;
415
0
                } else if (processingOption.match(2) == "NONE") {
416
0
                  this->Deduplication = None;
417
0
                } else if (processingOption.match(2) == "SHARED") {
418
0
                  this->Deduplication = Shared;
419
0
                } else {
420
0
                  errorMessage =
421
0
                    cmStrCat(std::move(errorMessage), "  ", option, '\n');
422
0
                }
423
0
              }
424
0
            } else {
425
0
              errorMessage =
426
0
                cmStrCat(std::move(errorMessage), "  ", option, '\n');
427
0
            }
428
0
          }
429
0
          if (!errorMessage.empty()) {
430
0
            makefile->GetCMakeInstance()->IssueMessage(
431
0
              MessageType::FATAL_ERROR,
432
0
              cmStrCat("Erroneous option(s) for 'CMAKE_", linkLanguage,
433
0
                       "_LINK_LIBRARIES_PROCESSING':\n", errorMessage),
434
0
              target->GetBacktrace());
435
0
          }
436
          // For some environments, deduplication should be activated only if
437
          // both policies CMP0156 and CMP0179 are NEW
438
0
          if (makefile->GetDefinition(cmStrCat(
439
0
                "CMAKE_", linkLanguage, "_PLATFORM_LINKER_ID")) == "LLD"_s &&
440
0
              makefile->GetDefinition("CMAKE_EXECUTABLE_FORMAT") == "ELF"_s &&
441
0
              target->GetPolicyStatusCMP0179() != cmPolicies::NEW &&
442
0
              this->Deduplication == All) {
443
0
            this->Deduplication = Shared;
444
0
          }
445
0
        }
446
0
      }
447
0
    }
448
0
  }
449
450
  void AddGroups(std::map<size_t, std::vector<size_t>> const& groups)
451
0
  {
452
0
    if (!groups.empty()) {
453
0
      this->Groups = &groups;
454
      // record all libraries as part of groups to ensure correct
455
      // deduplication: libraries as part of groups are always kept.
456
0
      for (auto const& g : groups) {
457
0
        for (auto index : g.second) {
458
0
          this->Emitted.insert(index);
459
0
        }
460
0
      }
461
0
    }
462
0
  }
463
464
  void AddLibraries(std::vector<size_t> const& libEntries)
465
0
  {
466
0
    if (this->Order == Reverse) {
467
0
      std::vector<size_t> entries;
468
0
      if (this->Deduplication == All &&
469
0
          this->Target->GetPolicyStatusCMP0179() == cmPolicies::NEW) {
470
        // keep the first occurrence of the static libraries
471
0
        std::set<size_t> emitted{ this->Emitted };
472
0
        for (auto index : libEntries) {
473
0
          LinkEntry const& entry = this->Entries[index];
474
0
          if (!entry.Target ||
475
0
              entry.Target->GetType() != cm::TargetType::STATIC_LIBRARY) {
476
0
            entries.emplace_back(index);
477
0
            continue;
478
0
          }
479
0
          if (this->IncludeEntry(entry) || emitted.insert(index).second) {
480
0
            entries.emplace_back(index);
481
0
          }
482
0
        }
483
0
      } else {
484
0
        entries = libEntries;
485
0
      }
486
      // Iterate in reverse order so we can keep only the last occurrence
487
      // of the shared libraries.
488
0
      this->AddLibraries(cmReverseRange(entries));
489
0
    } else {
490
0
      this->AddLibraries(cmMakeRange(libEntries));
491
0
    }
492
0
  }
493
494
  void AddObjects(std::vector<size_t> const& objectEntries)
495
0
  {
496
    // Place explicitly linked object files in the front.  The linker will
497
    // always use them anyway, and they may depend on symbols from libraries.
498
0
    if (this->Order == Reverse) {
499
      // Append in reverse order at the end since we reverse the final order.
500
0
      for (auto index : cmReverseRange(objectEntries)) {
501
0
        this->FinalEntries.emplace_back(this->Entries[index]);
502
0
      }
503
0
    } else {
504
      // Append in reverse order to ensure correct final order
505
0
      for (auto index : cmReverseRange(objectEntries)) {
506
0
        this->FinalEntries.emplace(this->FinalEntries.begin(),
507
0
                                   this->Entries[index]);
508
0
      }
509
0
    }
510
0
  }
511
512
  void Finalize()
513
0
  {
514
0
    if (this->Order == Reverse) {
515
      // Reverse the resulting order since we iterated in reverse.
516
0
      std::reverse(this->FinalEntries.begin(), this->FinalEntries.end());
517
0
    }
518
519
    // expand groups
520
0
    if (this->Groups) {
521
0
      for (auto const& g : *this->Groups) {
522
0
        LinkEntry const& groupEntry = this->Entries[g.first];
523
0
        auto it = this->FinalEntries.begin();
524
0
        while (true) {
525
0
          it = std::find_if(it, this->FinalEntries.end(),
526
0
                            [&groupEntry](LinkEntry const& entry) -> bool {
527
0
                              return groupEntry.Item == entry.Item;
528
0
                            });
529
0
          if (it == this->FinalEntries.end()) {
530
0
            break;
531
0
          }
532
0
          it->Item.Value = std::string(LG_ITEM_END);
533
0
          for (auto index = g.second.rbegin(); index != g.second.rend();
534
0
               ++index) {
535
0
            it = this->FinalEntries.insert(it, this->Entries[*index]);
536
0
          }
537
0
          it = this->FinalEntries.insert(it, groupEntry);
538
0
          it->Item.Value = std::string(LG_ITEM_BEGIN);
539
0
        }
540
0
      }
541
0
    }
542
0
  }
543
544
private:
545
  enum OrderKind
546
  {
547
    Forward,
548
    Reverse
549
  };
550
551
  enum DeduplicationKind
552
  {
553
    None,
554
    Shared,
555
    All
556
  };
557
558
  bool IncludeEntry(LinkEntry const& entry) const
559
0
  {
560
0
    if (entry.Feature != cmComputeLinkDepends::LinkEntry::DEFAULT) {
561
0
      auto const& featureAttributes = GetLinkLibraryFeatureAttributes(
562
0
        this->Target->Makefile, this->LinkLanguage, entry.Feature);
563
0
      if ((!entry.Target ||
564
0
           featureAttributes.LibraryTypes.find(entry.Target->GetType()) !=
565
0
             featureAttributes.LibraryTypes.end()) &&
566
0
          featureAttributes.Deduplication !=
567
0
            LinkLibraryFeatureAttributeSet::Default) {
568
0
        return featureAttributes.Deduplication ==
569
0
          LinkLibraryFeatureAttributeSet::No;
570
0
      }
571
0
    }
572
573
0
    return this->Deduplication == None ||
574
0
      (this->Deduplication == Shared &&
575
0
       (!entry.Target ||
576
0
        entry.Target->GetType() != cm::TargetType::SHARED_LIBRARY)) ||
577
0
      (this->Deduplication == All && entry.Kind != LinkEntry::Library);
578
0
  }
579
580
  template <typename Range>
581
  void AddLibraries(Range const& libEntries)
582
0
  {
583
0
    for (auto index : libEntries) {
584
0
      LinkEntry const& entry = this->Entries[index];
585
0
      if (this->IncludeEntry(entry) || this->Emitted.insert(index).second) {
586
0
        this->FinalEntries.emplace_back(entry);
587
0
      }
588
0
    }
589
0
  }
Unexecuted instantiation: cmComputeLinkDepends.cxx:void (anonymous namespace)::EntriesProcessing::AddLibraries<cmRange<std::__1::reverse_iterator<std::__1::__wrap_iter<unsigned long const*> > > >(cmRange<std::__1::reverse_iterator<std::__1::__wrap_iter<unsigned long const*> > > const&)
Unexecuted instantiation: cmComputeLinkDepends.cxx:void (anonymous namespace)::EntriesProcessing::AddLibraries<cmRange<std::__1::__wrap_iter<unsigned long const*> > >(cmRange<std::__1::__wrap_iter<unsigned long const*> > const&)
590
591
  OrderKind Order = Reverse;
592
  DeduplicationKind Deduplication = Shared;
593
  cmGeneratorTarget const* Target;
594
  std::string const& LinkLanguage;
595
  EntryVector& Entries;
596
  EntryVector& FinalEntries;
597
  std::set<size_t> Emitted;
598
  std::map<size_t, std::vector<size_t>> const* Groups = nullptr;
599
};
600
}
601
602
std::string const& cmComputeLinkDepends::LinkEntry::DEFAULT =
603
  cmLinkItem::DEFAULT;
604
605
cmComputeLinkDepends::cmComputeLinkDepends(cmGeneratorTarget const* target,
606
                                           std::string config,
607
                                           std::string linkLanguage,
608
                                           LinkLibrariesStrategy strategy)
609
0
  : Target(target)
610
0
  , Makefile(this->Target->Target->GetMakefile())
611
0
  , GlobalGenerator(this->Target->GetLocalGenerator()->GetGlobalGenerator())
612
0
  , CMakeInstance(this->GlobalGenerator->GetCMakeInstance())
613
0
  , Config(std::move(config))
614
0
  , DebugMode(this->Makefile->IsOn("CMAKE_LINK_DEPENDS_DEBUG_MODE") ||
615
0
              this->Target->GetProperty("LINK_DEPENDS_DEBUG_MODE").IsOn())
616
0
  , LinkLanguage(std::move(linkLanguage))
617
0
  , LinkType(ComputeLinkType(
618
0
      this->Config, this->Makefile->GetCMakeInstance()->GetDebugConfigs()))
619
0
  , Strategy(strategy)
620
621
0
{
622
0
  cm::GenEx::Context context(this->Target->LocalGenerator, this->Config,
623
0
                             this->LinkLanguage);
624
  // target oriented feature override property takes precedence over
625
  // global override property
626
0
  cm::string_view lloPrefix = "LINK_LIBRARY_OVERRIDE_"_s;
627
0
  auto const& keys = this->Target->GetPropertyKeys();
628
0
  std::for_each(
629
0
    keys.cbegin(), keys.cend(),
630
0
    [this, &lloPrefix, &context](std::string const& key) {
631
0
      if (cmHasPrefix(key, lloPrefix)) {
632
0
        if (cmValue feature = this->Target->GetProperty(key)) {
633
0
          if (!feature->empty() && key.length() > lloPrefix.length()) {
634
0
            auto item = key.substr(lloPrefix.length());
635
0
            cmGeneratorExpressionDAGChecker dagChecker{
636
0
              this->Target, "LINK_LIBRARY_OVERRIDE",      nullptr, nullptr,
637
0
              context,      this->Target->GetBacktrace(),
638
0
            };
639
0
            auto overrideFeature = cmGeneratorExpression::Evaluate(
640
0
              *feature, context.LG, context.Config, this->Target, &dagChecker,
641
0
              this->Target, context.Language);
642
0
            this->LinkLibraryOverride.emplace(item, overrideFeature);
643
0
          }
644
0
        }
645
0
      }
646
0
    });
647
  // global override property
648
0
  if (cmValue linkLibraryOverride =
649
0
        this->Target->GetProperty("LINK_LIBRARY_OVERRIDE")) {
650
0
    cmGeneratorExpressionDAGChecker dagChecker{
651
0
      this->Target, "LINK_LIBRARY_OVERRIDE",      nullptr, nullptr,
652
0
      context,      this->Target->GetBacktrace(),
653
0
    };
654
0
    auto overrideValue = cmGeneratorExpression::Evaluate(
655
0
      *linkLibraryOverride, context.LG, context.Config, this->Target,
656
0
      &dagChecker, this->Target, context.Language);
657
658
0
    std::vector<std::string> overrideList =
659
0
      cmTokenize(overrideValue, ',', cmTokenizerMode::New);
660
0
    if (overrideList.size() >= 2) {
661
0
      auto const& feature = overrideList.front();
662
0
      std::for_each(overrideList.cbegin() + 1, overrideList.cend(),
663
0
                    [this, &feature](std::string const& item) {
664
0
                      this->LinkLibraryOverride.emplace(item, feature);
665
0
                    });
666
0
    }
667
0
  }
668
0
}
669
670
0
cmComputeLinkDepends::~cmComputeLinkDepends() = default;
671
672
std::vector<cmComputeLinkDepends::LinkEntry> const&
673
cmComputeLinkDepends::Compute()
674
0
{
675
  // Follow the link dependencies of the target to be linked.
676
0
  this->AddDirectLinkEntries();
677
678
  // Complete the breadth-first search of dependencies.
679
0
  while (!this->BFSQueue.empty()) {
680
    // Get the next entry.
681
0
    BFSEntry qe = this->BFSQueue.front();
682
0
    this->BFSQueue.pop();
683
684
    // Follow the entry's dependencies.
685
0
    this->FollowLinkEntry(qe);
686
0
  }
687
688
  // Complete the search of shared library dependencies.
689
0
  while (!this->SharedDepQueue.empty()) {
690
    // Handle the next entry.
691
0
    this->HandleSharedDependency(this->SharedDepQueue.front());
692
0
    this->SharedDepQueue.pop();
693
0
  }
694
695
  // Infer dependencies of targets for which they were not known.
696
0
  this->InferDependencies();
697
698
  // finalize groups dependencies
699
  // All dependencies which are raw items must be replaced by the group
700
  // it belongs to, if any.
701
0
  this->UpdateGroupDependencies();
702
703
  // Cleanup the constraint graph.
704
0
  this->CleanConstraintGraph();
705
706
  // Display the constraint graph.
707
0
  if (this->DebugMode) {
708
0
    fprintf(stderr,
709
0
            "---------------------------------------"
710
0
            "---------------------------------------\n");
711
0
    fprintf(stderr, "Link dependency analysis for target %s, config %s\n",
712
0
            this->Target->GetName().c_str(),
713
0
            this->Config.empty() ? "noconfig" : this->Config.c_str());
714
0
    this->DisplayConstraintGraph();
715
0
  }
716
717
  // Compute the DAG of strongly connected components.  The algorithm
718
  // used by cmComputeComponentGraph should identify the components in
719
  // the same order in which the items were originally discovered in
720
  // the BFS.  This should preserve the original order when no
721
  // constraints disallow it.
722
0
  this->CCG =
723
0
    cm::make_unique<cmComputeComponentGraph>(this->EntryConstraintGraph);
724
0
  this->CCG->Compute();
725
726
0
  if (!this->CheckCircularDependencies()) {
727
0
    return this->FinalLinkEntries;
728
0
  }
729
730
  // Compute the final ordering.
731
0
  this->OrderLinkEntries();
732
733
  // Display the final ordering.
734
0
  if (this->DebugMode) {
735
0
    this->DisplayOrderedEntries();
736
0
  }
737
738
  // Compute the final set of link entries.
739
0
  EntriesProcessing entriesProcessing{ this->Target, this->LinkLanguage,
740
0
                                       this->EntryList,
741
0
                                       this->FinalLinkEntries };
742
  // Add groups first, to ensure that libraries of the groups are always kept.
743
0
  entriesProcessing.AddGroups(this->GroupItems);
744
0
  entriesProcessing.AddLibraries(this->FinalLinkOrder);
745
0
  entriesProcessing.AddObjects(this->ObjectEntries);
746
0
  entriesProcessing.Finalize();
747
748
  // Display the final set.
749
0
  if (this->DebugMode) {
750
0
    this->DisplayFinalEntries();
751
0
  }
752
753
0
  return this->FinalLinkEntries;
754
0
}
755
756
std::string const& cmComputeLinkDepends::GetCurrentFeature(
757
  std::string const& item, std::string const& defaultFeature) const
758
0
{
759
0
  auto it = this->LinkLibraryOverride.find(item);
760
0
  return it == this->LinkLibraryOverride.end() ? defaultFeature : it->second;
761
0
}
762
763
std::pair<std::map<cmLinkItem, size_t>::iterator, bool>
764
cmComputeLinkDepends::AllocateLinkEntry(cmLinkItem const& item)
765
0
{
766
0
  std::map<cmLinkItem, size_t>::value_type index_entry(
767
0
    item, static_cast<size_t>(this->EntryList.size()));
768
0
  auto lei = this->LinkEntryIndex.insert(index_entry);
769
0
  if (lei.second) {
770
0
    this->EntryList.emplace_back();
771
0
    this->InferredDependSets.emplace_back();
772
0
    this->EntryConstraintGraph.emplace_back();
773
0
  }
774
0
  return lei;
775
0
}
776
777
std::pair<size_t, bool> cmComputeLinkDepends::AddLinkEntry(
778
  cmLinkItem const& item, cm::optional<size_t> groupIndex)
779
0
{
780
  // Allocate a spot for the item entry.
781
0
  auto lei = this->AllocateLinkEntry(item);
782
783
  // Check if the item entry has already been added.
784
0
  if (!lei.second) {
785
    // Yes.  We do not need to follow the item's dependencies again.
786
0
    return { lei.first->second, false };
787
0
  }
788
789
  // Initialize the item entry.
790
0
  size_t index = lei.first->second;
791
0
  LinkEntry& entry = this->EntryList[index];
792
0
  entry.Item = BT<std::string>(item.AsStr(), item.Backtrace);
793
0
  entry.Target = item.Target;
794
0
  entry.Feature = item.Feature;
795
0
  if (!entry.Target && entry.Item.Value[0] == '-' &&
796
0
      entry.Item.Value[1] != 'l' &&
797
0
      entry.Item.Value.substr(0, 10) != "-framework") {
798
0
    entry.Kind = LinkEntry::Flag;
799
0
    entry.Feature = LinkEntry::DEFAULT;
800
0
  } else if (cmHasPrefix(entry.Item.Value, LG_BEGIN) &&
801
0
             cmHasSuffix(entry.Item.Value, '>')) {
802
0
    entry.Kind = LinkEntry::Group;
803
0
  }
804
805
0
  if (entry.Kind != LinkEntry::Group) {
806
    // If the item has dependencies queue it to follow them.
807
0
    if (entry.Target) {
808
      // Target dependencies are always known.  Follow them.
809
0
      BFSEntry qe = { index, groupIndex, nullptr };
810
0
      this->BFSQueue.push(qe);
811
0
    } else {
812
      // Look for an old-style <item>_LIB_DEPENDS variable.
813
0
      std::string var = cmStrCat(entry.Item.Value, "_LIB_DEPENDS");
814
0
      if (cmValue val = this->Makefile->GetDefinition(var)) {
815
        // The item dependencies are known.  Follow them.
816
0
        BFSEntry qe = { index, groupIndex, val->c_str() };
817
0
        this->BFSQueue.push(qe);
818
0
      } else if (entry.Kind != LinkEntry::Flag) {
819
        // The item dependencies are not known.  We need to infer them.
820
0
        this->InferredDependSets[index].Initialized = true;
821
0
      }
822
0
    }
823
0
  }
824
825
0
  return { index, true };
826
0
}
827
828
void cmComputeLinkDepends::AddLinkObject(cmLinkItem const& item)
829
0
{
830
0
  assert(!item.Target); // The item is an object file, not its target.
831
832
  // Allocate a spot for the item entry.
833
0
  auto lei = this->AllocateLinkEntry(item);
834
835
  // Check if the item entry has already been added.
836
0
  if (!lei.second) {
837
0
    return;
838
0
  }
839
840
  // Initialize the item entry.
841
0
  size_t index = lei.first->second;
842
0
  LinkEntry& entry = this->EntryList[index];
843
0
  entry.Item = BT<std::string>(item.AsStr(), item.Backtrace);
844
0
  entry.Kind = LinkEntry::Object;
845
0
  entry.ObjectSource = item.ObjectSource;
846
847
  // Record explicitly linked object files separately.
848
0
  this->ObjectEntries.emplace_back(index);
849
0
}
850
851
void cmComputeLinkDepends::FollowLinkEntry(BFSEntry qe)
852
0
{
853
  // Get this entry representation.
854
0
  size_t depender_index = qe.GroupIndex ? *qe.GroupIndex : qe.Index;
855
0
  LinkEntry const& entry = this->EntryList[qe.Index];
856
857
  // Follow the item's dependencies.
858
0
  if (entry.Target) {
859
    // Follow the target dependencies.
860
0
    if (cmLinkInterface const* iface =
861
0
          entry.Target->GetLinkInterface(this->Config, this->Target)) {
862
0
      bool const isIface =
863
0
        entry.Target->GetType() == cm::TargetType::INTERFACE_LIBRARY;
864
      // This target provides its own link interface information.
865
0
      this->AddLinkEntries(depender_index, iface->Libraries);
866
0
      this->AddLinkObjects(iface->Objects);
867
0
      for (auto const& language : iface->Languages) {
868
0
        auto runtimeEntries = iface->LanguageRuntimeLibraries.find(language);
869
0
        if (runtimeEntries != iface->LanguageRuntimeLibraries.end()) {
870
0
          this->AddLinkEntries(depender_index, runtimeEntries->second);
871
0
        }
872
0
      }
873
874
0
      if (isIface) {
875
0
        return;
876
0
      }
877
878
      // Handle dependent shared libraries.
879
0
      this->FollowSharedDeps(depender_index, iface);
880
0
    }
881
0
  } else {
882
    // Follow the old-style dependency list.
883
0
    this->AddVarLinkEntries(depender_index, qe.LibDepends);
884
0
  }
885
0
}
886
887
void cmComputeLinkDepends::FollowSharedDeps(size_t depender_index,
888
                                            cmLinkInterface const* iface,
889
                                            bool follow_interface)
890
0
{
891
  // Follow dependencies if we have not followed them already.
892
0
  if (this->SharedDepFollowed.insert(depender_index).second) {
893
0
    if (follow_interface) {
894
0
      this->QueueSharedDependencies(depender_index, iface->Libraries);
895
0
    }
896
0
    this->QueueSharedDependencies(depender_index, iface->SharedDeps);
897
0
  }
898
0
}
899
900
void cmComputeLinkDepends::QueueSharedDependencies(
901
  size_t depender_index, std::vector<cmLinkItem> const& deps)
902
0
{
903
0
  for (cmLinkItem const& li : deps) {
904
0
    SharedDepEntry qe;
905
0
    qe.Item = li;
906
0
    qe.DependerIndex = depender_index;
907
0
    this->SharedDepQueue.push(qe);
908
0
  }
909
0
}
910
911
void cmComputeLinkDepends::HandleSharedDependency(SharedDepEntry const& dep)
912
0
{
913
  // Allocate a spot for the item entry.
914
0
  auto lei = this->AllocateLinkEntry(dep.Item);
915
0
  size_t index = lei.first->second;
916
917
  // Check if the target does not already has an entry.
918
0
  if (lei.second) {
919
    // Initialize the item entry.
920
0
    LinkEntry& entry = this->EntryList[index];
921
0
    entry.Item = BT<std::string>(dep.Item.AsStr(), dep.Item.Backtrace);
922
0
    entry.Target = dep.Item.Target;
923
924
    // This item was added specifically because it is a dependent
925
    // shared library.  It may get special treatment
926
    // in cmComputeLinkInformation.
927
0
    entry.Kind = LinkEntry::SharedDep;
928
0
  }
929
930
  // Get the link entry for this target.
931
0
  LinkEntry& entry = this->EntryList[index];
932
933
  // This shared library dependency must follow the item that listed
934
  // it.
935
0
  this->EntryConstraintGraph[dep.DependerIndex].emplace_back(
936
0
    index, true, false, cmListFileBacktrace());
937
938
  // Target items may have their own dependencies.
939
0
  if (entry.Target) {
940
0
    if (cmLinkInterface const* iface =
941
0
          entry.Target->GetLinkInterface(this->Config, this->Target)) {
942
      // Follow public and private dependencies transitively.
943
0
      this->FollowSharedDeps(index, iface, true);
944
0
    }
945
0
  }
946
0
}
947
948
void cmComputeLinkDepends::AddVarLinkEntries(
949
  cm::optional<size_t> depender_index, char const* value)
950
0
{
951
  // This is called to add the dependencies named by
952
  // <item>_LIB_DEPENDS.  The variable contains a semicolon-separated
953
  // list.  The list contains link-type;item pairs and just items.
954
0
  cmList deplist{ value };
955
956
  // Look for entries meant for this configuration.
957
0
  std::vector<cmLinkItem> actual_libs;
958
0
  cmTargetLinkLibraryType llt = GENERAL_LibraryType;
959
0
  bool haveLLT = false;
960
0
  for (std::string const& d : deplist) {
961
0
    if (d == "debug") {
962
0
      llt = DEBUG_LibraryType;
963
0
      haveLLT = true;
964
0
    } else if (d == "optimized") {
965
0
      llt = OPTIMIZED_LibraryType;
966
0
      haveLLT = true;
967
0
    } else if (d == "general") {
968
0
      llt = GENERAL_LibraryType;
969
0
      haveLLT = true;
970
0
    } else if (!d.empty()) {
971
      // If no explicit link type was given prior to this entry then
972
      // check if the entry has its own link type variable.  This is
973
      // needed for compatibility with dependency files generated by
974
      // the export_library_dependencies command from CMake 2.4 and
975
      // lower.
976
0
      if (!haveLLT) {
977
0
        std::string var = cmStrCat(d, "_LINK_TYPE");
978
0
        if (cmValue val = this->Makefile->GetDefinition(var)) {
979
0
          if (*val == "debug") {
980
0
            llt = DEBUG_LibraryType;
981
0
          } else if (*val == "optimized") {
982
0
            llt = OPTIMIZED_LibraryType;
983
0
          }
984
0
        }
985
0
      }
986
987
      // If the library is meant for this link type then use it.
988
0
      if (llt == GENERAL_LibraryType || llt == this->LinkType) {
989
0
        actual_libs.emplace_back(this->ResolveLinkItem(depender_index, d));
990
0
      }
991
992
      // Reset the link type until another explicit type is given.
993
0
      llt = GENERAL_LibraryType;
994
0
      haveLLT = false;
995
0
    }
996
0
  }
997
998
  // Add the entries from this list.
999
0
  this->AddLinkEntries(depender_index, actual_libs);
1000
0
}
1001
1002
void cmComputeLinkDepends::AddDirectLinkEntries()
1003
0
{
1004
  // Add direct link dependencies in this configuration.
1005
0
  cmLinkImplementation const* impl = this->Target->GetLinkImplementation(
1006
0
    this->Config, cmGeneratorTarget::UseTo::Link);
1007
0
  this->AddLinkEntries(cm::nullopt, impl->Libraries);
1008
0
  this->AddLinkObjects(impl->Objects);
1009
1010
0
  for (auto const& language : impl->Languages) {
1011
0
    auto runtimeEntries = impl->LanguageRuntimeLibraries.find(language);
1012
0
    if (runtimeEntries != impl->LanguageRuntimeLibraries.end()) {
1013
0
      this->AddLinkEntries(cm::nullopt, runtimeEntries->second);
1014
0
    }
1015
0
  }
1016
0
}
1017
1018
template <typename T>
1019
void cmComputeLinkDepends::AddLinkEntries(cm::optional<size_t> depender_index,
1020
                                          std::vector<T> const& libs)
1021
0
{
1022
  // Track inferred dependency sets implied by this list.
1023
0
  std::map<size_t, DependSet> dependSets;
1024
1025
0
  cm::optional<std::pair<size_t, bool>> group;
1026
0
  std::vector<size_t> groupItems;
1027
1028
  // Loop over the libraries linked directly by the depender.
1029
0
  for (T const& l : libs) {
1030
    // Skip entries that will resolve to the target getting linked or
1031
    // are empty.
1032
0
    cmLinkItem const& item = l;
1033
0
    if (item.AsStr() == this->Target->GetName() || item.AsStr().empty()) {
1034
0
      continue;
1035
0
    }
1036
1037
    // emit a warning if an undefined feature is used as part of
1038
    // an imported target
1039
0
    if (item.Feature != LinkEntry::DEFAULT && depender_index) {
1040
0
      auto const& depender = this->EntryList[*depender_index];
1041
0
      if (depender.Target && depender.Target->IsImported() &&
1042
0
          !IsFeatureSupported(this->Makefile, this->LinkLanguage,
1043
0
                              item.Feature)) {
1044
0
        this->CMakeInstance->IssueDiagnostic(
1045
0
          cmDiagnostics::CMD_AUTHOR,
1046
0
          cmStrCat("The 'IMPORTED' target '", depender.Target->GetName(),
1047
0
                   "' uses the generator-expression '$<LINK_LIBRARY>' with "
1048
0
                   "the feature '",
1049
0
                   item.Feature,
1050
0
                   "', which is undefined or unsupported.\nDid you miss to "
1051
0
                   "define it by setting variables \"CMAKE_",
1052
0
                   this->LinkLanguage, "_LINK_LIBRARY_USING_", item.Feature,
1053
0
                   "\" and \"CMAKE_", this->LinkLanguage,
1054
0
                   "_LINK_LIBRARY_USING_", item.Feature, "_SUPPORTED\"?"),
1055
0
          this->Target->GetBacktrace());
1056
0
      }
1057
0
    }
1058
1059
0
    if (cmHasPrefix(item.AsStr(), LG_BEGIN) &&
1060
0
        cmHasSuffix(item.AsStr(), '>')) {
1061
0
      group = this->AddLinkEntry(item, cm::nullopt);
1062
0
      if (group->second) {
1063
0
        LinkEntry& entry = this->EntryList[group->first];
1064
0
        entry.Feature = ExtractGroupFeature(item.AsStr());
1065
0
      }
1066
0
      if (depender_index) {
1067
0
        this->EntryConstraintGraph[*depender_index].emplace_back(
1068
0
          group->first, false, false, cmListFileBacktrace());
1069
0
      } else {
1070
        // This is a direct dependency of the target being linked.
1071
0
        this->OriginalEntries.push_back(group->first);
1072
0
      }
1073
0
      continue;
1074
0
    }
1075
1076
0
    size_t dependee_index;
1077
1078
0
    if (cmHasPrefix(item.AsStr(), LG_END) && cmHasSuffix(item.AsStr(), '>')) {
1079
0
      assert(group);
1080
0
      dependee_index = group->first;
1081
0
      if (group->second) {
1082
0
        this->GroupItems.emplace(group->first, std::move(groupItems));
1083
0
      }
1084
0
      group = cm::nullopt;
1085
0
      groupItems.clear();
1086
0
      continue;
1087
0
    }
1088
1089
0
    if (depender_index && group) {
1090
0
      auto const& depender = this->EntryList[*depender_index];
1091
0
      auto const& groupFeature = this->EntryList[group->first].Feature;
1092
0
      if (depender.Target && depender.Target->IsImported() &&
1093
0
          !IsGroupFeatureSupported(this->Makefile, this->LinkLanguage,
1094
0
                                   groupFeature)) {
1095
0
        this->CMakeInstance->IssueDiagnostic(
1096
0
          cmDiagnostics::CMD_AUTHOR,
1097
0
          cmStrCat("The 'IMPORTED' target '", depender.Target->GetName(),
1098
0
                   "' uses the generator-expression '$<LINK_GROUP>' with "
1099
0
                   "the feature '",
1100
0
                   groupFeature,
1101
0
                   "', which is undefined or unsupported.\nDid you miss to "
1102
0
                   "define it by setting variables \"CMAKE_",
1103
0
                   this->LinkLanguage, "_LINK_GROUP_USING_", groupFeature,
1104
0
                   "\" and \"CMAKE_", this->LinkLanguage, "_LINK_GROUP_USING_",
1105
0
                   groupFeature, "_SUPPORTED\"?"),
1106
0
          this->Target->GetBacktrace());
1107
0
      }
1108
0
    }
1109
1110
    // Add a link entry for this item.
1111
0
    auto ale = this->AddLinkEntry(
1112
0
      item, group ? cm::optional<size_t>(group->first) : cm::nullopt);
1113
0
    dependee_index = ale.first;
1114
0
    LinkEntry& entry = this->EntryList[dependee_index];
1115
0
    bool supportedItem = true;
1116
0
    std::string itemFeature =
1117
0
      this->GetCurrentFeature(entry.Item.Value, item.Feature);
1118
0
    if (entry.Target &&
1119
0
        entry.Target->GetType() == cm::TargetType::STATIC_LIBRARY &&
1120
0
        entry.Target->GetPropertyAsBool("SYCL_RESOLVE_DEVICE_SYMBOLS") &&
1121
0
        (entry.Target->IsImported() ||
1122
0
         entry.Target->Makefile->IsOn(
1123
0
           "CMAKE_SYCL_COMPILER_HAS_DEVICE_LINK_PHASE"))) {
1124
0
      if (itemFeature != LinkEntry::DEFAULT &&
1125
0
          itemFeature != "WHOLE_ARCHIVE") {
1126
0
        this->CMakeInstance->IssueMessage(
1127
0
          MessageType::FATAL_ERROR,
1128
0
          cmStrCat("Finalized SYCL static library \"", entry.Item.Value,
1129
0
                   "\" requires the WHOLE_ARCHIVE link-library feature."),
1130
0
          this->Target->GetBacktrace());
1131
0
      }
1132
0
      itemFeature = "WHOLE_ARCHIVE";
1133
0
    }
1134
0
    if (group && ale.second && entry.Target &&
1135
0
        (entry.Target->GetType() == cm::TargetType::OBJECT_LIBRARY ||
1136
0
         entry.Target->GetType() == cm::TargetType::INTERFACE_LIBRARY)) {
1137
0
      supportedItem = false;
1138
0
      auto const& groupFeature = this->EntryList[group->first].Feature;
1139
0
      this->CMakeInstance->IssueDiagnostic(
1140
0
        cmDiagnostics::CMD_AUTHOR,
1141
0
        cmStrCat("The feature '", groupFeature,
1142
0
                 "', specified as part of a generator-expression "
1143
0
                 "'$",
1144
0
                 LG_BEGIN, groupFeature, ">', will not be applied to the ",
1145
0
                 (entry.Target->GetType() == cm::TargetType::OBJECT_LIBRARY
1146
0
                    ? "OBJECT"
1147
0
                    : "INTERFACE"),
1148
0
                 " library '", entry.Item.Value, "'."),
1149
0
        this->Target->GetBacktrace());
1150
0
    }
1151
    // check if feature is applicable to this item
1152
0
    if (itemFeature != LinkEntry::DEFAULT && entry.Target) {
1153
0
      auto const& featureAttributes = GetLinkLibraryFeatureAttributes(
1154
0
        this->Makefile, this->LinkLanguage, itemFeature);
1155
0
      if (featureAttributes.LibraryTypes.find(entry.Target->GetType()) ==
1156
0
          featureAttributes.LibraryTypes.end()) {
1157
0
        supportedItem = false;
1158
0
        this->CMakeInstance->IssueDiagnostic(
1159
0
          cmDiagnostics::CMD_AUTHOR,
1160
0
          cmStrCat("The feature '", itemFeature,
1161
0
                   "', specified as part of a generator-expression "
1162
0
                   "'$<LINK_LIBRARY:",
1163
0
                   itemFeature, ">', will not be applied to the ",
1164
0
                   cmState::GetTargetTypeName(entry.Target->GetType()), " '",
1165
0
                   entry.Item.Value, "'."),
1166
0
          this->Target->GetBacktrace());
1167
0
      }
1168
0
    }
1169
0
    if (ale.second) {
1170
      // current item not yet defined
1171
0
      entry.Feature = itemFeature;
1172
0
      if (!supportedItem) {
1173
0
        entry.Feature = LinkEntry::DEFAULT;
1174
0
      }
1175
0
    }
1176
1177
0
    if (supportedItem) {
1178
0
      if (group) {
1179
0
        auto const& currentFeature = this->EntryList[group->first].Feature;
1180
0
        for (auto const& g : this->GroupItems) {
1181
0
          auto const& groupFeature = this->EntryList[g.first].Feature;
1182
0
          if (groupFeature == currentFeature) {
1183
0
            continue;
1184
0
          }
1185
0
          if (std::find(g.second.cbegin(), g.second.cend(), dependee_index) !=
1186
0
              g.second.cend()) {
1187
0
            this->CMakeInstance->IssueMessage(
1188
0
              MessageType::FATAL_ERROR,
1189
0
              cmStrCat("Impossible to link target '", this->Target->GetName(),
1190
0
                       "' because the link item '", entry.Item.Value,
1191
0
                       "', specified with the group feature '", currentFeature,
1192
0
                       "', has already occurred with the feature '",
1193
0
                       groupFeature, "', which is not allowed."),
1194
0
              this->Target->GetBacktrace());
1195
0
            continue;
1196
0
          }
1197
0
        }
1198
0
      }
1199
0
      if (entry.Feature != itemFeature) {
1200
0
        bool incompatibleFeatures = true;
1201
        // check if an override is possible
1202
0
        auto const& entryFeatureAttributes = GetLinkLibraryFeatureAttributes(
1203
0
          this->Makefile, this->LinkLanguage, entry.Feature);
1204
0
        auto const& itemFeatureAttributes = GetLinkLibraryFeatureAttributes(
1205
0
          this->Makefile, this->LinkLanguage, itemFeature);
1206
0
        if (itemFeatureAttributes.Override.find(entry.Feature) !=
1207
0
              itemFeatureAttributes.Override.end() &&
1208
0
            entryFeatureAttributes.Override.find(itemFeature) !=
1209
0
              entryFeatureAttributes.Override.end()) {
1210
          // features override each other
1211
0
          this->CMakeInstance->IssueMessage(
1212
0
            MessageType::FATAL_ERROR,
1213
0
            cmStrCat("Impossible to link target '", this->Target->GetName(),
1214
0
                     "' because the link item '", entry.Item.Value,
1215
0
                     "' is specified with the features '", itemFeature,
1216
0
                     "' and '", entry.Feature,
1217
0
                     "'"
1218
0
                     ", and both have an 'OVERRIDE' attribute that overrides "
1219
0
                     "the other. Such cycles are not allowed."),
1220
0
            this->Target->GetBacktrace());
1221
0
        } else {
1222
0
          if (itemFeatureAttributes.Override.find(entry.Feature) !=
1223
0
              itemFeatureAttributes.Override.end()) {
1224
0
            entry.Feature = itemFeature;
1225
0
            incompatibleFeatures = false;
1226
0
          } else if (entryFeatureAttributes.Override.find(itemFeature) !=
1227
0
                     entryFeatureAttributes.Override.end()) {
1228
0
            incompatibleFeatures = false;
1229
0
          }
1230
0
          if (incompatibleFeatures) {
1231
            // incompatibles features occurred
1232
0
            this->CMakeInstance->IssueMessage(
1233
0
              MessageType::FATAL_ERROR,
1234
0
              cmStrCat(
1235
0
                "Impossible to link target '", this->Target->GetName(),
1236
0
                "' because the link item '", entry.Item.Value, "', specified ",
1237
0
                (itemFeature == LinkEntry::DEFAULT
1238
0
                   ? "without any feature or 'DEFAULT' feature"
1239
0
                   : cmStrCat("with the feature '", itemFeature, '\'')),
1240
0
                ", has already occurred ",
1241
0
                (entry.Feature == LinkEntry::DEFAULT
1242
0
                   ? "without any feature or 'DEFAULT' feature"
1243
0
                   : cmStrCat("with the feature '", entry.Feature, '\'')),
1244
0
                ", which is not allowed."),
1245
0
              this->Target->GetBacktrace());
1246
0
          }
1247
0
        }
1248
0
      }
1249
0
    }
1250
1251
0
    if (group) {
1252
      // store item index for dependencies handling
1253
0
      groupItems.push_back(dependee_index);
1254
0
    } else {
1255
0
      std::vector<size_t> indexes;
1256
0
      bool entryHandled = false;
1257
      // search any occurrence of the library in already defined groups
1258
0
      for (auto const& g : this->GroupItems) {
1259
0
        for (auto index : g.second) {
1260
0
          if (entry.Item.Value == this->EntryList[index].Item.Value) {
1261
0
            indexes.push_back(g.first);
1262
0
            entryHandled = true;
1263
0
            break;
1264
0
          }
1265
0
        }
1266
0
      }
1267
0
      if (!entryHandled) {
1268
0
        indexes.push_back(dependee_index);
1269
0
      }
1270
1271
0
      for (auto index : indexes) {
1272
        // The dependee must come after the depender.
1273
0
        if (depender_index) {
1274
0
          this->EntryConstraintGraph[*depender_index].emplace_back(
1275
0
            index, false, false, cmListFileBacktrace());
1276
0
        } else {
1277
          // This is a direct dependency of the target being linked.
1278
0
          this->OriginalEntries.push_back(index);
1279
0
        }
1280
1281
        // Update the inferred dependencies for earlier items.
1282
0
        for (auto& dependSet : dependSets) {
1283
          // Add this item to the inferred dependencies of other items.
1284
          // Target items are never inferred dependees because unknown
1285
          // items are outside libraries that should not be depending on
1286
          // targets.
1287
0
          if (!this->EntryList[index].Target &&
1288
0
              this->EntryList[index].Kind != LinkEntry::Flag &&
1289
0
              this->EntryList[index].Kind != LinkEntry::Group &&
1290
0
              dependee_index != dependSet.first) {
1291
0
            dependSet.second.insert(index);
1292
0
          }
1293
0
        }
1294
1295
        // If this item needs to have dependencies inferred, do so.
1296
0
        if (this->InferredDependSets[index].Initialized) {
1297
          // Make sure an entry exists to hold the set for the item.
1298
0
          dependSets[index];
1299
0
        }
1300
0
      }
1301
0
    }
1302
0
  }
1303
1304
  // Store the inferred dependency sets discovered for this list.
1305
0
  for (auto const& dependSet : dependSets) {
1306
0
    this->InferredDependSets[dependSet.first].push_back(dependSet.second);
1307
0
  }
1308
0
}
1309
1310
void cmComputeLinkDepends::AddLinkObjects(std::vector<cmLinkItem> const& objs)
1311
0
{
1312
0
  for (cmLinkItem const& obj : objs) {
1313
0
    this->AddLinkObject(obj);
1314
0
  }
1315
0
}
1316
1317
cmLinkItem cmComputeLinkDepends::ResolveLinkItem(
1318
  cm::optional<size_t> depender_index, std::string const& name)
1319
0
{
1320
  // Look for a target in the scope of the depender.
1321
0
  cmGeneratorTarget const* from = this->Target;
1322
0
  if (depender_index) {
1323
0
    if (cmGeneratorTarget const* depender =
1324
0
          this->EntryList[*depender_index].Target) {
1325
0
      from = depender;
1326
0
    }
1327
0
  }
1328
0
  return from->ResolveLinkItem(BT<std::string>(name));
1329
0
}
1330
1331
void cmComputeLinkDepends::InferDependencies()
1332
0
{
1333
  // The inferred dependency sets for each item list the possible
1334
  // dependencies.  The intersection of the sets for one item form its
1335
  // inferred dependencies.
1336
0
  for (size_t depender_index = 0;
1337
0
       depender_index < this->InferredDependSets.size(); ++depender_index) {
1338
    // Skip items for which dependencies do not need to be inferred or
1339
    // for which the inferred dependency sets are empty.
1340
0
    DependSetList& sets = this->InferredDependSets[depender_index];
1341
0
    if (!sets.Initialized || sets.empty()) {
1342
0
      continue;
1343
0
    }
1344
1345
    // Intersect the sets for this item.
1346
0
    DependSet common = sets.front();
1347
0
    for (DependSet const& i : cmMakeRange(sets).advance(1)) {
1348
0
      DependSet intersection;
1349
0
      std::set_intersection(common.begin(), common.end(), i.begin(), i.end(),
1350
0
                            std::inserter(intersection, intersection.begin()));
1351
0
      common = intersection;
1352
0
    }
1353
1354
    // Add the inferred dependencies to the graph.
1355
0
    cmGraphEdgeList& edges = this->EntryConstraintGraph[depender_index];
1356
0
    edges.reserve(edges.size() + common.size());
1357
0
    for (auto const& c : common) {
1358
0
      edges.emplace_back(c, true, false, cmListFileBacktrace());
1359
0
    }
1360
0
  }
1361
0
}
1362
1363
void cmComputeLinkDepends::UpdateGroupDependencies()
1364
0
{
1365
0
  if (this->GroupItems.empty()) {
1366
0
    return;
1367
0
  }
1368
1369
  // Walks through all entries of the constraint graph to replace dependencies
1370
  // over raw items by the group it belongs to, if any.
1371
0
  for (auto& edgeList : this->EntryConstraintGraph) {
1372
0
    for (auto& edge : edgeList) {
1373
0
      size_t index = edge;
1374
0
      if (this->EntryList[index].Kind == LinkEntry::Group ||
1375
0
          this->EntryList[index].Kind == LinkEntry::Flag ||
1376
0
          this->EntryList[index].Kind == LinkEntry::Object) {
1377
0
        continue;
1378
0
      }
1379
      // search the item in the defined groups
1380
0
      for (auto const& groupItems : this->GroupItems) {
1381
0
        auto pos = std::find(groupItems.second.cbegin(),
1382
0
                             groupItems.second.cend(), index);
1383
0
        if (pos != groupItems.second.cend()) {
1384
          // replace lib dependency by the group it belongs to
1385
0
          edge = cmGraphEdge{ groupItems.first, false, false,
1386
0
                              cmListFileBacktrace() };
1387
0
        }
1388
0
      }
1389
0
    }
1390
0
  }
1391
0
}
1392
1393
void cmComputeLinkDepends::CleanConstraintGraph()
1394
0
{
1395
0
  for (cmGraphEdgeList& edgeList : this->EntryConstraintGraph) {
1396
    // Sort the outgoing edges for each graph node so that the
1397
    // original order will be preserved as much as possible.
1398
0
    std::sort(edgeList.begin(), edgeList.end());
1399
1400
    // Make the edge list unique.
1401
0
    edgeList.erase(std::unique(edgeList.begin(), edgeList.end()),
1402
0
                   edgeList.end());
1403
0
  }
1404
0
}
1405
1406
bool cmComputeLinkDepends::CheckCircularDependencies() const
1407
0
{
1408
0
  std::vector<NodeList> const& components = this->CCG->GetComponents();
1409
0
  size_t nc = components.size();
1410
0
  for (size_t c = 0; c < nc; ++c) {
1411
    // Get the current component.
1412
0
    NodeList const& nl = components[c];
1413
1414
    // Skip trivial components.
1415
0
    if (nl.size() < 2) {
1416
0
      continue;
1417
0
    }
1418
1419
    // no group must be evolved
1420
0
    bool cycleDetected = false;
1421
0
    for (size_t ni : nl) {
1422
0
      if (this->EntryList[ni].Kind == LinkEntry::Group) {
1423
0
        cycleDetected = true;
1424
0
        break;
1425
0
      }
1426
0
    }
1427
0
    if (!cycleDetected) {
1428
0
      continue;
1429
0
    }
1430
1431
    // Construct the error message.
1432
0
    auto formatItem = [](LinkEntry const& entry) -> std::string {
1433
0
      if (entry.Kind == LinkEntry::Group) {
1434
0
        auto items =
1435
0
          entry.Item.Value.substr(entry.Item.Value.find(':', 12) + 1);
1436
0
        items.pop_back();
1437
0
        std::replace(items.begin(), items.end(), '|', ',');
1438
0
        return cmStrCat("group \"", ExtractGroupFeature(entry.Item.Value),
1439
0
                        ":{", items, "}\"");
1440
0
      }
1441
0
      return cmStrCat('"', entry.Item.Value, '"');
1442
0
    };
1443
1444
0
    std::ostringstream e;
1445
0
    e << "The inter-target dependency graph, for the target \""
1446
0
      << this->Target->GetName()
1447
0
      << "\", contains the following strongly connected component "
1448
0
         "(cycle):\n";
1449
0
    std::vector<size_t> const& cmap = this->CCG->GetComponentMap();
1450
0
    for (size_t i : nl) {
1451
      // Get the depender.
1452
0
      LinkEntry const& depender = this->EntryList[i];
1453
1454
      // Describe the depender.
1455
0
      e << "  " << formatItem(depender) << "\n";
1456
1457
      // List its dependencies that are inside the component.
1458
0
      EdgeList const& el = this->EntryConstraintGraph[i];
1459
0
      for (cmGraphEdge const& ni : el) {
1460
0
        size_t j = ni;
1461
0
        if (cmap[j] == c) {
1462
0
          LinkEntry const& dependee = this->EntryList[j];
1463
0
          e << "    depends on " << formatItem(dependee) << "\n";
1464
0
        }
1465
0
      }
1466
0
    }
1467
0
    this->CMakeInstance->IssueMessage(MessageType::FATAL_ERROR, e.str(),
1468
0
                                      this->Target->GetBacktrace());
1469
1470
0
    return false;
1471
0
  }
1472
1473
0
  return true;
1474
0
}
1475
1476
void cmComputeLinkDepends::DisplayConstraintGraph()
1477
0
{
1478
  // Display the graph nodes and their edges.
1479
0
  std::ostringstream e;
1480
0
  for (size_t i = 0; i < this->EntryConstraintGraph.size(); ++i) {
1481
0
    EdgeList const& nl = this->EntryConstraintGraph[i];
1482
0
    e << "item " << i << " is [" << this->EntryList[i].Item << "]\n";
1483
0
    e << cmWrap("  item ", nl, " must follow it", "\n") << "\n";
1484
0
  }
1485
0
  fprintf(stderr, "%s\n", e.str().c_str());
1486
0
}
1487
1488
void cmComputeLinkDepends::OrderLinkEntries()
1489
0
{
1490
  // The component graph is guaranteed to be acyclic.  Start a DFS
1491
  // from every entry to compute a topological order for the
1492
  // components.
1493
0
  Graph const& cgraph = this->CCG->GetComponentGraph();
1494
0
  size_t n = cgraph.size();
1495
0
  this->ComponentVisited.resize(cgraph.size(), 0);
1496
0
  this->ComponentOrder.resize(cgraph.size(), n);
1497
0
  this->ComponentOrderId = n;
1498
  // Run in reverse order so the topological order will preserve the
1499
  // original order where there are no constraints.
1500
0
  for (size_t c = n; c > 0; --c) {
1501
0
    this->VisitComponent(c - 1);
1502
0
  }
1503
1504
  // Display the component graph.
1505
0
  if (this->DebugMode) {
1506
0
    this->DisplayComponents();
1507
0
  }
1508
1509
  // Start with the original link line.
1510
0
  switch (this->Strategy) {
1511
0
    case LinkLibrariesStrategy::REORDER_MINIMALLY: {
1512
      // Emit the direct dependencies in their original order.
1513
      // This gives projects control over ordering.
1514
0
      for (size_t originalEntry : this->OriginalEntries) {
1515
0
        this->VisitEntry(originalEntry);
1516
0
      }
1517
0
    } break;
1518
0
    case LinkLibrariesStrategy::REORDER_FREELY: {
1519
      // Schedule the direct dependencies for emission in topo order.
1520
      // This may produce more efficient link lines.
1521
0
      for (size_t originalEntry : this->OriginalEntries) {
1522
0
        this->MakePendingComponent(
1523
0
          this->CCG->GetComponentMap()[originalEntry]);
1524
0
      }
1525
0
    } break;
1526
0
  }
1527
1528
  // Now explore anything left pending.  Since the component graph is
1529
  // guaranteed to be acyclic we know this will terminate.
1530
0
  while (!this->PendingComponents.empty()) {
1531
    // Visit one entry from the first pending component.  The visit
1532
    // logic will update the pending components accordingly.  Since
1533
    // the pending components are kept in topological order this will
1534
    // not repeat one.
1535
0
    size_t e = *this->PendingComponents.begin()->second.Entries.begin();
1536
0
    this->VisitEntry(e);
1537
0
  }
1538
0
}
1539
1540
void cmComputeLinkDepends::DisplayComponents()
1541
0
{
1542
0
  fprintf(stderr, "The strongly connected components are:\n");
1543
0
  std::vector<NodeList> const& components = this->CCG->GetComponents();
1544
0
  for (size_t c = 0; c < components.size(); ++c) {
1545
0
    fprintf(stderr, "Component (%zu):\n", c);
1546
0
    NodeList const& nl = components[c];
1547
0
    for (size_t i : nl) {
1548
0
      fprintf(stderr, "  item %zu [%s]\n", i,
1549
0
              this->EntryList[i].Item.Value.c_str());
1550
0
    }
1551
0
    EdgeList const& ol = this->CCG->GetComponentGraphEdges(c);
1552
0
    for (cmGraphEdge const& oi : ol) {
1553
0
      size_t i = oi;
1554
0
      fprintf(stderr, "  followed by Component (%zu)\n", i);
1555
0
    }
1556
0
    fprintf(stderr, "  topo order index %zu\n", this->ComponentOrder[c]);
1557
0
  }
1558
0
  fprintf(stderr, "\n");
1559
0
}
1560
1561
void cmComputeLinkDepends::VisitComponent(size_t c)
1562
0
{
1563
  // Check if the node has already been visited.
1564
0
  if (this->ComponentVisited[c]) {
1565
0
    return;
1566
0
  }
1567
1568
  // We are now visiting this component so mark it.
1569
0
  this->ComponentVisited[c] = 1;
1570
1571
  // Visit the neighbors of the component first.
1572
  // Run in reverse order so the topological order will preserve the
1573
  // original order where there are no constraints.
1574
0
  EdgeList const& nl = this->CCG->GetComponentGraphEdges(c);
1575
0
  for (cmGraphEdge const& edge : cmReverseRange(nl)) {
1576
0
    this->VisitComponent(edge);
1577
0
  }
1578
1579
  // Assign an ordering id to this component.
1580
0
  this->ComponentOrder[c] = --this->ComponentOrderId;
1581
0
}
1582
1583
void cmComputeLinkDepends::VisitEntry(size_t index)
1584
0
{
1585
  // Include this entry on the link line.
1586
0
  this->FinalLinkOrder.push_back(index);
1587
1588
  // This entry has now been seen.  Update its component.
1589
0
  bool completed = false;
1590
0
  size_t component = this->CCG->GetComponentMap()[index];
1591
0
  auto mi = this->PendingComponents.find(this->ComponentOrder[component]);
1592
0
  if (mi != this->PendingComponents.end()) {
1593
    // The entry is in an already pending component.
1594
0
    PendingComponent& pc = mi->second;
1595
1596
    // Remove the entry from those pending in its component.
1597
0
    pc.Entries.erase(index);
1598
0
    if (pc.Entries.empty()) {
1599
      // The complete component has been seen since it was last needed.
1600
0
      --pc.Count;
1601
1602
0
      if (pc.Count == 0) {
1603
        // The component has been completed.
1604
0
        this->PendingComponents.erase(mi);
1605
0
        completed = true;
1606
0
      } else {
1607
        // The whole component needs to be seen again.
1608
0
        NodeList const& nl = this->CCG->GetComponent(component);
1609
0
        assert(nl.size() > 1);
1610
0
        pc.Entries.insert(nl.begin(), nl.end());
1611
0
      }
1612
0
    }
1613
0
  } else {
1614
    // The entry is not in an already pending component.
1615
0
    NodeList const& nl = this->CCG->GetComponent(component);
1616
0
    if (nl.size() > 1) {
1617
      // This is a non-trivial component.  It is now pending.
1618
0
      PendingComponent& pc = this->MakePendingComponent(component);
1619
1620
      // The starting entry has already been seen.
1621
0
      pc.Entries.erase(index);
1622
0
    } else {
1623
      // This is a trivial component, so it is already complete.
1624
0
      completed = true;
1625
0
    }
1626
0
  }
1627
1628
  // If the entry completed a component, the component's dependencies
1629
  // are now pending.
1630
0
  if (completed) {
1631
0
    EdgeList const& ol = this->CCG->GetComponentGraphEdges(component);
1632
0
    for (cmGraphEdge const& oi : ol) {
1633
      // This entire component is now pending no matter whether it has
1634
      // been partially seen already.
1635
0
      this->MakePendingComponent(oi);
1636
0
    }
1637
0
  }
1638
0
}
1639
1640
cmComputeLinkDepends::PendingComponent&
1641
cmComputeLinkDepends::MakePendingComponent(size_t component)
1642
0
{
1643
  // Create an entry (in topological order) for the component.
1644
0
  PendingComponent& pc =
1645
0
    this->PendingComponents[this->ComponentOrder[component]];
1646
0
  pc.Id = component;
1647
0
  NodeList const& nl = this->CCG->GetComponent(component);
1648
1649
0
  if (nl.size() == 1) {
1650
    // Trivial components need be seen only once.
1651
0
    pc.Count = 1;
1652
0
  } else {
1653
    // This is a non-trivial strongly connected component of the
1654
    // original graph.  It consists of two or more libraries
1655
    // (archives) that mutually require objects from one another.  In
1656
    // the worst case we may have to repeat the list of libraries as
1657
    // many times as there are object files in the biggest archive.
1658
    // For now we just list them twice.
1659
    //
1660
    // The list of items in the component has been sorted by the order
1661
    // of discovery in the original BFS of dependencies.  This has the
1662
    // advantage that the item directly linked by a target requiring
1663
    // this component will come first which minimizes the number of
1664
    // repeats needed.
1665
0
    pc.Count = this->ComputeComponentCount(nl);
1666
0
  }
1667
1668
  // Store the entries to be seen.
1669
0
  pc.Entries.insert(nl.begin(), nl.end());
1670
1671
0
  return pc;
1672
0
}
1673
1674
size_t cmComputeLinkDepends::ComputeComponentCount(NodeList const& nl)
1675
0
{
1676
0
  size_t count = 2;
1677
0
  for (size_t ni : nl) {
1678
0
    if (cmGeneratorTarget const* target = this->EntryList[ni].Target) {
1679
0
      if (cmLinkInterface const* iface =
1680
0
            target->GetLinkInterface(this->Config, this->Target)) {
1681
0
        if (iface->Multiplicity > count) {
1682
0
          count = iface->Multiplicity;
1683
0
        }
1684
0
      }
1685
0
    }
1686
0
  }
1687
0
  return count;
1688
0
}
1689
1690
namespace {
1691
void DisplayLinkEntry(int& count, cmComputeLinkDepends::LinkEntry const& entry)
1692
0
{
1693
0
  if (entry.Kind == cmComputeLinkDepends::LinkEntry::Group) {
1694
0
    if (entry.Item.Value == LG_ITEM_BEGIN) {
1695
0
      fprintf(stderr, "  start group");
1696
0
      count = 4;
1697
0
    } else if (entry.Item.Value == LG_ITEM_END) {
1698
0
      fprintf(stderr, "  end group");
1699
0
      count = 2;
1700
0
    } else {
1701
0
      fprintf(stderr, "  group");
1702
0
    }
1703
0
  } else if (entry.Target) {
1704
0
    fprintf(stderr, "%*starget [%s]", count, "",
1705
0
            entry.Target->GetName().c_str());
1706
0
  } else {
1707
0
    fprintf(stderr, "%*sitem [%s]", count, "", entry.Item.Value.c_str());
1708
0
  }
1709
0
  if (entry.Feature != cmComputeLinkDepends::LinkEntry::DEFAULT) {
1710
0
    fprintf(stderr, ", feature [%s]", entry.Feature.c_str());
1711
0
  }
1712
0
  fprintf(stderr, "\n");
1713
0
}
1714
}
1715
1716
void cmComputeLinkDepends::DisplayOrderedEntries()
1717
0
{
1718
0
  fprintf(stderr, "target [%s] link dependency ordering:\n",
1719
0
          this->Target->GetName().c_str());
1720
0
  int count = 2;
1721
0
  for (auto index : this->FinalLinkOrder) {
1722
0
    DisplayLinkEntry(count, this->EntryList[index]);
1723
0
  }
1724
0
  fprintf(stderr, "\n");
1725
0
}
1726
1727
void cmComputeLinkDepends::DisplayFinalEntries()
1728
0
{
1729
0
  fprintf(stderr, "target [%s] link line:\n", this->Target->GetName().c_str());
1730
0
  int count = 2;
1731
0
  for (LinkEntry const& entry : this->FinalLinkEntries) {
1732
0
    DisplayLinkEntry(count, entry);
1733
0
  }
1734
  fprintf(stderr, "\n");
1735
0
}