Coverage Report

Created: 2026-07-14 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Source/cmGeneratorTarget.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 "cmGeneratorTarget.h"
4
5
#include <algorithm>
6
#include <array>
7
#include <cassert>
8
#include <cstddef>
9
#include <cstdio>
10
#include <cstring>
11
#include <sstream>
12
#include <string>
13
#include <unordered_set>
14
#include <utility>
15
16
#include <cm/memory>
17
#include <cm/optional>
18
#include <cm/string_view>
19
#include <cmext/algorithm>
20
#include <cmext/string_view>
21
22
#include "cmsys/String.h"
23
24
#include "cmAlgorithms.h"
25
#include "cmComputeLinkInformation.h" // IWYU pragma: keep
26
#include "cmCryptoHash.h"
27
#include "cmCxxModuleMetadata.h"
28
#include "cmCxxModuleUsageEffects.h"
29
#include "cmExperimental.h"
30
#include "cmFileSet.h"
31
#include "cmFileSetMetadata.h"
32
#include "cmFileTimes.h"
33
#include "cmGenExContext.h"
34
#include "cmGeneratedFileStream.h"
35
#include "cmGeneratorExpression.h"
36
#include "cmGeneratorExpressionDAGChecker.h"
37
#include "cmGeneratorFileSet.h"
38
#include "cmGeneratorFileSets.h"
39
#include "cmGeneratorOptions.h"
40
#include "cmGlobalGenerator.h"
41
#include "cmList.h"
42
#include "cmLocalGenerator.h"
43
#include "cmMakefile.h"
44
#include "cmMessageType.h"
45
#include "cmOutputConverter.h"
46
#include "cmPropertyMap.h"
47
#include "cmRulePlaceholderExpander.h"
48
#include "cmSourceFile.h"
49
#include "cmSourceFileLocationKind.h"
50
#include "cmStandardLevel.h"
51
#include "cmStandardLevelResolver.h"
52
#include "cmState.h"
53
#include "cmStateTypes.h"
54
#include "cmStringAlgorithms.h"
55
#include "cmSystemTools.h"
56
#include "cmTarget.h"
57
#include "cmTargetLinkLibraryType.h"
58
#include "cmTargetPropertyComputer.h"
59
#include "cmTargetTraceDependencies.h"
60
#include "cmake.h"
61
62
namespace {
63
using UseTo = cmGeneratorTarget::UseTo;
64
}
65
66
template <>
67
cmValue cmTargetPropertyComputer::GetSources<cmGeneratorTarget>(
68
  cmGeneratorTarget const* tgt)
69
0
{
70
0
  return tgt->GetSourcesProperty();
71
0
}
72
73
template <>
74
std::string const&
75
cmTargetPropertyComputer::ImportedLocation<cmGeneratorTarget>(
76
  cmGeneratorTarget const* tgt, std::string const& config)
77
0
{
78
0
  return tgt->GetLocation(config);
79
0
}
80
81
static void CreatePropertyGeneratorExpressions(
82
  cmake& cmakeInstance, cmBTStringRange entries,
83
  std::vector<std::unique_ptr<cm::TargetPropertyEntry>>& items,
84
  bool evaluateForBuildsystem = false)
85
0
{
86
0
  for (auto const& entry : entries) {
87
0
    items.emplace_back(cm::TargetPropertyEntry::Create(
88
0
      cmakeInstance, entry, evaluateForBuildsystem));
89
0
  }
90
0
}
91
92
cmGeneratorTarget::cmGeneratorTarget(cmTarget* t, cmLocalGenerator* lg)
93
0
  : Target(t)
94
0
  , Makefile(t->GetMakefile())
95
0
  , LocalGenerator(lg)
96
0
  , GlobalGenerator(lg->GetGlobalGenerator())
97
0
  , FileSets(cm::make_unique<cmGeneratorFileSets>(this, lg))
98
0
{
99
0
  this->GlobalGenerator->ComputeTargetObjectDirectory(this);
100
101
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
102
0
                                     t->GetIncludeDirectoriesEntries(),
103
0
                                     this->IncludeDirectoriesEntries);
104
105
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
106
0
                                     t->GetCompileOptionsEntries(),
107
0
                                     this->CompileOptionsEntries);
108
109
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
110
0
                                     t->GetCompileFeaturesEntries(),
111
0
                                     this->CompileFeaturesEntries);
112
113
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
114
0
                                     t->GetCompileDefinitionsEntries(),
115
0
                                     this->CompileDefinitionsEntries);
116
117
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
118
0
                                     t->GetLinkOptionsEntries(),
119
0
                                     this->LinkOptionsEntries);
120
121
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
122
0
                                     t->GetLinkDirectoriesEntries(),
123
0
                                     this->LinkDirectoriesEntries);
124
125
0
  CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
126
0
                                     t->GetPrecompileHeadersEntries(),
127
0
                                     this->PrecompileHeadersEntries);
128
129
0
  CreatePropertyGeneratorExpressions(
130
0
    *lg->GetCMakeInstance(), t->GetSourceEntries(), this->SourceEntries, true);
131
132
0
  this->PolicyMap = t->GetPolicyMap();
133
134
  // Get hard-coded linker language
135
0
  if (this->Target->GetProperty("HAS_CXX")) {
136
0
    this->LinkerLanguage = "CXX";
137
0
  } else {
138
0
    this->LinkerLanguage = this->Target->GetSafeProperty("LINKER_LANGUAGE");
139
0
  }
140
141
0
  auto configs =
142
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
143
0
  std::string build_db_languages[] = { "CXX" };
144
0
  for (auto const& language : build_db_languages) {
145
0
    for (auto const& config : configs) {
146
0
      auto bdb_path = this->BuildDatabasePath(language, config);
147
0
      if (!bdb_path.empty()) {
148
0
        this->Makefile->GetOrCreateGeneratedSource(bdb_path);
149
0
        this->GetGlobalGenerator()->AddBuildDatabaseFile(language, config,
150
0
                                                         bdb_path);
151
0
      }
152
0
    }
153
0
  }
154
0
}
155
156
0
cmGeneratorTarget::~cmGeneratorTarget() = default;
157
158
cmValue cmGeneratorTarget::GetSourcesProperty() const
159
0
{
160
0
  std::vector<std::string> values;
161
0
  for (auto const& se : this->SourceEntries) {
162
0
    values.push_back(se->GetInput());
163
0
  }
164
0
  static std::string value;
165
0
  value = cmList::to_string(values);
166
0
  return cmValue(value);
167
0
}
168
169
cmGlobalGenerator* cmGeneratorTarget::GetGlobalGenerator() const
170
0
{
171
0
  return this->GetLocalGenerator()->GetGlobalGenerator();
172
0
}
173
174
cmLocalGenerator* cmGeneratorTarget::GetLocalGenerator() const
175
0
{
176
0
  return this->LocalGenerator;
177
0
}
178
179
cm::TargetType cmGeneratorTarget::GetType() const
180
0
{
181
0
  return this->Target->GetType();
182
0
}
183
184
std::string const& cmGeneratorTarget::GetName() const
185
0
{
186
0
  return this->Target->GetName();
187
0
}
188
189
std::string cmGeneratorTarget::GetFamilyName() const
190
0
{
191
0
  if (!this->IsImported() && !this->IsSynthetic()) {
192
0
    return this->Target->GetTemplateName();
193
0
  }
194
0
  cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_512);
195
0
  constexpr size_t HASH_TRUNCATION = 12;
196
0
  auto dirhash =
197
0
    hasher.HashString(this->GetLocalGenerator()->GetCurrentBinaryDirectory());
198
0
  auto targetIdent = hasher.HashString(cmStrCat("@d_", dirhash));
199
0
  return cmStrCat(this->Target->GetTemplateName(), '@',
200
0
                  targetIdent.substr(0, HASH_TRUNCATION));
201
0
}
202
203
std::string cmGeneratorTarget::GetExportName() const
204
0
{
205
0
  cmValue exportName = this->GetProperty("EXPORT_NAME");
206
207
0
  if (cmNonempty(exportName)) {
208
0
    if (!cmGeneratorExpression::IsValidTargetName(*exportName)) {
209
0
      std::ostringstream e;
210
0
      e << "EXPORT_NAME property \"" << *exportName << "\" for \""
211
0
        << this->GetName() << "\": is not valid.";
212
0
      cmSystemTools::Error(e.str());
213
0
      return "";
214
0
    }
215
0
    return *exportName;
216
0
  }
217
0
  return this->GetName();
218
0
}
219
220
std::string cmGeneratorTarget::GetFilesystemExportName() const
221
0
{
222
0
  auto fs_safe = this->GetExportName();
223
  // First escape any `_` characters to avoid collisions.
224
0
  cmSystemTools::ReplaceString(fs_safe, "_", "__");
225
  // Escape other characters that are not generally filesystem-safe.
226
0
  cmSystemTools::ReplaceString(fs_safe, ":", "_c");
227
0
  return fs_safe;
228
0
}
229
230
cmValue cmGeneratorTarget::GetProperty(std::string const& prop) const
231
0
{
232
0
  if (cmValue result =
233
0
        cmTargetPropertyComputer::GetProperty(this, prop, *this->Makefile)) {
234
0
    return result;
235
0
  }
236
0
  if (cmSystemTools::GetFatalErrorOccurred()) {
237
0
    return nullptr;
238
0
  }
239
0
  return this->Target->GetProperty(prop);
240
0
}
241
242
std::string const& cmGeneratorTarget::GetSafeProperty(
243
  std::string const& prop) const
244
0
{
245
0
  return this->GetProperty(prop);
246
0
}
247
248
char const* cmGeneratorTarget::GetOutputTargetType(
249
  cmStateEnums::ArtifactType artifact) const
250
0
{
251
0
  if (this->IsFrameworkOnApple() || this->GetGlobalGenerator()->IsXcode()) {
252
    // import file (i.e. .tbd file) is always in same location as library
253
0
    artifact = cmStateEnums::RuntimeBinaryArtifact;
254
0
  }
255
256
0
  switch (this->GetType()) {
257
0
    case cm::TargetType::SHARED_LIBRARY:
258
0
      if (this->IsDLLPlatform()) {
259
0
        switch (artifact) {
260
0
          case cmStateEnums::RuntimeBinaryArtifact:
261
            // A DLL shared library is treated as a runtime target.
262
0
            return "RUNTIME";
263
0
          case cmStateEnums::ImportLibraryArtifact:
264
            // A DLL import library is treated as an archive target.
265
0
            return "ARCHIVE";
266
0
        }
267
0
      } else {
268
0
        switch (artifact) {
269
0
          case cmStateEnums::RuntimeBinaryArtifact:
270
            // For non-DLL platforms shared libraries are treated as
271
            // library targets.
272
0
            return "LIBRARY";
273
0
          case cmStateEnums::ImportLibraryArtifact:
274
            // Library import libraries are treated as archive targets.
275
0
            return "ARCHIVE";
276
0
        }
277
0
      }
278
0
      break;
279
0
    case cm::TargetType::STATIC_LIBRARY:
280
      // Static libraries are always treated as archive targets.
281
0
      return "ARCHIVE";
282
0
    case cm::TargetType::MODULE_LIBRARY:
283
0
      switch (artifact) {
284
0
        case cmStateEnums::RuntimeBinaryArtifact:
285
          // Module libraries are always treated as library targets.
286
0
          return "LIBRARY";
287
0
        case cmStateEnums::ImportLibraryArtifact:
288
          // Module import libraries are treated as archive targets.
289
0
          return "ARCHIVE";
290
0
      }
291
0
      break;
292
0
    case cm::TargetType::OBJECT_LIBRARY:
293
      // Object libraries are always treated as object targets.
294
0
      return "OBJECT";
295
0
    case cm::TargetType::EXECUTABLE:
296
0
      switch (artifact) {
297
0
        case cmStateEnums::RuntimeBinaryArtifact:
298
          // Executables are always treated as runtime targets.
299
0
          return "RUNTIME";
300
0
        case cmStateEnums::ImportLibraryArtifact:
301
          // Executable import libraries are treated as archive targets.
302
0
          return "ARCHIVE";
303
0
      }
304
0
      break;
305
0
    default:
306
0
      break;
307
0
  }
308
0
  return "";
309
0
}
310
311
std::string cmGeneratorTarget::GetOutputName(
312
  std::string const& config, cmStateEnums::ArtifactType artifact) const
313
0
{
314
  // Lookup/compute/cache the output name for this configuration.
315
0
  OutputNameKey key(config, artifact);
316
0
  auto i = this->OutputNameMap.find(key);
317
0
  if (i == this->OutputNameMap.end()) {
318
    // Add empty name in map to detect potential recursion.
319
0
    OutputNameMapType::value_type entry(key, "");
320
0
    i = this->OutputNameMap.insert(entry).first;
321
322
    // Compute output name.
323
0
    std::vector<std::string> props;
324
0
    std::string type = this->GetOutputTargetType(artifact);
325
0
    std::string configUpper = cmSystemTools::UpperCase(config);
326
0
    if (!type.empty() && !configUpper.empty()) {
327
      // <ARCHIVE|LIBRARY|RUNTIME>_OUTPUT_NAME_<CONFIG>
328
0
      props.push_back(cmStrCat(type, "_OUTPUT_NAME_", configUpper));
329
0
    }
330
0
    if (!type.empty()) {
331
      // <ARCHIVE|LIBRARY|RUNTIME>_OUTPUT_NAME
332
0
      props.push_back(type + "_OUTPUT_NAME");
333
0
    }
334
0
    if (!configUpper.empty()) {
335
      // OUTPUT_NAME_<CONFIG>
336
0
      props.push_back("OUTPUT_NAME_" + configUpper);
337
      // <CONFIG>_OUTPUT_NAME
338
0
      props.push_back(configUpper + "_OUTPUT_NAME");
339
0
    }
340
    // OUTPUT_NAME
341
0
    props.emplace_back("OUTPUT_NAME");
342
343
0
    std::string outName;
344
0
    for (std::string const& p : props) {
345
0
      if (cmValue outNameProp = this->GetProperty(p)) {
346
0
        outName = *outNameProp;
347
0
        break;
348
0
      }
349
0
    }
350
351
0
    if (outName.empty()) {
352
0
      outName = this->GetName();
353
0
    }
354
355
    // Now evaluate genex and update the previously-prepared map entry.
356
0
    i->second =
357
0
      cmGeneratorExpression::Evaluate(outName, this->LocalGenerator, config);
358
0
  } else if (i->second.empty()) {
359
    // An empty map entry indicates we have been called recursively
360
    // from the above block.
361
0
    this->LocalGenerator->GetCMakeInstance()->IssueMessage(
362
0
      MessageType::FATAL_ERROR,
363
0
      cmStrCat("Target '", this->GetName(),
364
0
               "' OUTPUT_NAME depends on itself."),
365
0
      this->GetBacktrace());
366
0
  }
367
0
  return i->second;
368
0
}
369
370
std::string cmGeneratorTarget::GetFilePrefix(
371
  std::string const& config, cmStateEnums::ArtifactType artifact) const
372
0
{
373
0
  if (this->IsImported()) {
374
0
    cmValue prefix = this->GetFilePrefixInternal(config, artifact);
375
0
    return prefix ? *prefix : std::string();
376
0
  }
377
0
  return this->GetFullNameInternalComponents(config, artifact).prefix;
378
0
}
379
std::string cmGeneratorTarget::GetFileSuffix(
380
  std::string const& config, cmStateEnums::ArtifactType artifact) const
381
0
{
382
0
  if (this->IsImported()) {
383
0
    cmValue suffix = this->GetFileSuffixInternal(config, artifact);
384
0
    return suffix ? *suffix : std::string();
385
0
  }
386
0
  return this->GetFullNameInternalComponents(config, artifact).suffix;
387
0
}
388
389
std::string cmGeneratorTarget::GetFilePostfix(std::string const& config) const
390
0
{
391
0
  cmValue postfix = nullptr;
392
0
  std::string frameworkPostfix;
393
0
  if (!config.empty()) {
394
0
    std::string configProp =
395
0
      cmStrCat(cmSystemTools::UpperCase(config), "_POSTFIX");
396
0
    postfix = this->GetProperty(configProp);
397
398
    // Mac application bundles and frameworks have no regular postfix like
399
    // libraries do.
400
0
    if (!this->IsImported() && postfix &&
401
0
        (this->IsAppBundleOnApple() || this->IsFrameworkOnApple())) {
402
0
      postfix = nullptr;
403
0
    }
404
405
    // Frameworks created by multi config generators can have a special
406
    // framework postfix.
407
0
    frameworkPostfix = this->GetFrameworkMultiConfigPostfix(config);
408
0
    if (!frameworkPostfix.empty()) {
409
0
      postfix = cmValue(frameworkPostfix);
410
0
    }
411
0
  }
412
0
  return postfix ? *postfix : std::string();
413
0
}
414
415
std::string cmGeneratorTarget::GetFrameworkMultiConfigPostfix(
416
  std::string const& config) const
417
0
{
418
0
  cmValue postfix = nullptr;
419
0
  if (!config.empty()) {
420
0
    std::string configProp = cmStrCat("FRAMEWORK_MULTI_CONFIG_POSTFIX_",
421
0
                                      cmSystemTools::UpperCase(config));
422
0
    postfix = this->GetProperty(configProp);
423
424
0
    if (!this->IsImported() && postfix &&
425
0
        (this->IsFrameworkOnApple() &&
426
0
         !this->GetGlobalGenerator()->IsMultiConfig())) {
427
0
      postfix = nullptr;
428
0
    }
429
0
  }
430
0
  return postfix ? *postfix : std::string();
431
0
}
432
433
cmValue cmGeneratorTarget::GetFilePrefixInternal(
434
  std::string const& config, cmStateEnums::ArtifactType artifact,
435
  std::string const& language) const
436
0
{
437
  // no prefix for non-main target types.
438
0
  if (this->GetType() != cm::TargetType::STATIC_LIBRARY &&
439
0
      this->GetType() != cm::TargetType::SHARED_LIBRARY &&
440
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
441
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
442
0
    return nullptr;
443
0
  }
444
445
0
  bool const isImportedLibraryArtifact =
446
0
    (artifact == cmStateEnums::ImportLibraryArtifact);
447
448
  // Return an empty prefix for the import library if this platform
449
  // does not support import libraries.
450
0
  if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
451
0
    return nullptr;
452
0
  }
453
454
  // The implib option is only allowed for shared libraries, module
455
  // libraries, and executables.
456
0
  if (this->GetType() != cm::TargetType::SHARED_LIBRARY &&
457
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
458
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
459
0
    artifact = cmStateEnums::RuntimeBinaryArtifact;
460
0
  }
461
462
  // Compute prefix value.
463
0
  cmValue targetPrefix =
464
0
    (isImportedLibraryArtifact ? this->GetProperty("IMPORT_PREFIX")
465
0
                               : this->GetProperty("PREFIX"));
466
467
0
  if (!targetPrefix) {
468
0
    char const* prefixVar = this->Target->GetPrefixVariableInternal(artifact);
469
0
    if (!language.empty() && cmNonempty(prefixVar)) {
470
0
      std::string langPrefix = cmStrCat(prefixVar, '_', language);
471
0
      targetPrefix = this->Makefile->GetDefinition(langPrefix);
472
0
    }
473
474
    // if there is no prefix on the target nor specific language
475
    // use the cmake definition.
476
0
    if (!targetPrefix && prefixVar) {
477
0
      targetPrefix = this->Makefile->GetDefinition(prefixVar);
478
0
    }
479
0
  }
480
481
0
  return targetPrefix;
482
0
}
483
484
cmValue cmGeneratorTarget::GetFileSuffixInternal(
485
  std::string const& config, cmStateEnums::ArtifactType artifact,
486
  std::string const& language) const
487
0
{
488
  // no suffix for non-main target types.
489
0
  if (this->GetType() != cm::TargetType::STATIC_LIBRARY &&
490
0
      this->GetType() != cm::TargetType::SHARED_LIBRARY &&
491
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
492
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
493
0
    return nullptr;
494
0
  }
495
496
0
  bool const isImportedLibraryArtifact =
497
0
    (artifact == cmStateEnums::ImportLibraryArtifact);
498
499
  // Return an empty suffix for the import library if this platform
500
  // does not support import libraries.
501
0
  if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
502
0
    return nullptr;
503
0
  }
504
505
  // The implib option is only allowed for shared libraries, module
506
  // libraries, and executables.
507
0
  if (this->GetType() != cm::TargetType::SHARED_LIBRARY &&
508
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
509
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
510
0
    artifact = cmStateEnums::RuntimeBinaryArtifact;
511
0
  }
512
513
  // Compute suffix value.
514
0
  cmValue targetSuffix =
515
0
    (isImportedLibraryArtifact ? this->GetProperty("IMPORT_SUFFIX")
516
0
                               : this->GetProperty("SUFFIX"));
517
518
0
  if (!targetSuffix) {
519
0
    char const* suffixVar = this->Target->GetSuffixVariableInternal(artifact);
520
0
    if (!language.empty() && cmNonempty(suffixVar)) {
521
0
      std::string langSuffix = cmStrCat(suffixVar, '_', language);
522
0
      targetSuffix = this->Makefile->GetDefinition(langSuffix);
523
0
    }
524
525
    // if there is no suffix on the target nor specific language
526
    // use the cmake definition.
527
0
    if (!targetSuffix && suffixVar) {
528
0
      targetSuffix = this->Makefile->GetDefinition(suffixVar);
529
0
    }
530
0
  }
531
532
0
  return targetSuffix;
533
0
}
534
535
void cmGeneratorTarget::ClearSourcesCache()
536
0
{
537
0
  this->AllConfigSources.clear();
538
0
  this->AllConfigCompileLanguages.clear();
539
0
  this->KindedSourcesMap.clear();
540
0
  this->SourcesAreContextDependent = Tribool::Indeterminate;
541
0
  this->Objects.clear();
542
0
  this->VisitedConfigsForObjects.clear();
543
0
  this->LinkImplClosureForLinkMap.clear();
544
0
  this->LinkImplClosureForUsageMap.clear();
545
0
  this->LinkImplMap.clear();
546
0
  this->LinkImplUsageRequirementsOnlyMap.clear();
547
0
  this->IncludeDirectoriesCache.clear();
548
0
  this->CompileOptionsCache.clear();
549
0
  this->CompileDefinitionsCache.clear();
550
0
  this->CustomTransitiveBuildPropertiesMap.clear();
551
0
  this->CustomTransitiveInterfacePropertiesMap.clear();
552
0
  this->PrecompileHeadersCache.clear();
553
0
  this->LinkOptionsCache.clear();
554
0
  this->LinkDirectoriesCache.clear();
555
0
  this->RuntimeBinaryFullNameCache.clear();
556
0
  this->ImportLibraryFullNameCache.clear();
557
0
}
558
559
void cmGeneratorTarget::ClearLinkInterfaceCache()
560
0
{
561
0
  this->LinkInterfaceMap.clear();
562
0
  this->LinkInterfaceUsageRequirementsOnlyMap.clear();
563
0
}
564
565
void cmGeneratorTarget::AddSourceCommon(std::string const& src, bool before)
566
0
{
567
0
  this->SourceEntries.insert(
568
0
    before ? this->SourceEntries.begin() : this->SourceEntries.end(),
569
0
    TargetPropertyEntry::Create(
570
0
      *this->LocalGenerator->GetCMakeInstance(),
571
0
      BT<std::string>(src, this->Makefile->GetBacktrace()), true));
572
0
  this->ClearSourcesCache();
573
0
}
574
575
cmSourceFile* cmGeneratorTarget::AddSource(std::string const& src, bool before)
576
0
{
577
0
  auto* sf = this->Target->AddSource(src, before);
578
0
  this->AddSourceCommon(src, before);
579
0
  return sf;
580
0
}
581
582
void cmGeneratorTarget::AddTracedSources(std::vector<std::string> const& srcs)
583
0
{
584
0
  this->Target->AddTracedSources(srcs);
585
0
  if (!srcs.empty()) {
586
0
    this->AddSourceCommon(cmJoin(srcs, ";"));
587
0
  }
588
0
}
589
590
void cmGeneratorTarget::AddIncludeDirectory(std::string const& src,
591
                                            bool before)
592
0
{
593
0
  this->Target->InsertInclude(
594
0
    BT<std::string>(src, this->Makefile->GetBacktrace()), before);
595
0
  this->IncludeDirectoriesEntries.insert(
596
0
    before ? this->IncludeDirectoriesEntries.begin()
597
0
           : this->IncludeDirectoriesEntries.end(),
598
0
    TargetPropertyEntry::Create(
599
0
      *this->Makefile->GetCMakeInstance(),
600
0
      BT<std::string>(src, this->Makefile->GetBacktrace()), true));
601
0
}
602
603
void cmGeneratorTarget::AddSystemIncludeDirectory(std::string const& inc,
604
                                                  std::string const& lang)
605
0
{
606
0
  std::string config_upper;
607
0
  auto const& configs =
608
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
609
610
0
  for (auto const& config : configs) {
611
0
    std::string inc_with_config = inc;
612
0
    if (!config.empty()) {
613
0
      cmSystemTools::ReplaceString(inc_with_config, "$<CONFIG>", config);
614
0
      config_upper = cmSystemTools::UpperCase(config);
615
0
    }
616
0
    auto const& key = cmStrCat(config_upper, '/', lang);
617
0
    this->Target->AddSystemIncludeDirectories({ inc_with_config });
618
0
    if (this->SystemIncludesCache.find(key) ==
619
0
        this->SystemIncludesCache.end()) {
620
0
      this->AddSystemIncludeCacheKey(key, config, lang);
621
0
    }
622
0
    this->SystemIncludesCache[key].emplace_back(inc_with_config);
623
624
    // SystemIncludesCache should be sorted so that binary search can be used
625
0
    std::sort(this->SystemIncludesCache[key].begin(),
626
0
              this->SystemIncludesCache[key].end());
627
0
  }
628
0
}
629
630
std::vector<cmSourceFile*> const* cmGeneratorTarget::GetSourceDepends(
631
  cmSourceFile const* sf) const
632
0
{
633
0
  auto i = this->SourceDepends.find(sf);
634
0
  if (i != this->SourceDepends.end()) {
635
0
    return &i->second.Depends;
636
0
  }
637
0
  return nullptr;
638
0
}
639
640
namespace {
641
void handleSystemIncludesDep(cmLocalGenerator const* lg,
642
                             cmGeneratorTarget const* depTgt,
643
                             std::string const& config,
644
                             cmGeneratorTarget const* headTarget,
645
                             cmGeneratorExpressionDAGChecker* dagChecker,
646
                             cmList& result, bool excludeImported,
647
                             std::string const& language)
648
0
{
649
0
  if (cmValue dirs =
650
0
        depTgt->GetProperty("INTERFACE_SYSTEM_INCLUDE_DIRECTORIES")) {
651
0
    result.append(cmGeneratorExpression::Evaluate(
652
0
      *dirs, lg, config, headTarget, dagChecker, depTgt, language));
653
0
  }
654
0
  if (!depTgt->GetPropertyAsBool("SYSTEM")) {
655
0
    return;
656
0
  }
657
0
  if (depTgt->IsImported()) {
658
0
    if (excludeImported) {
659
0
      return;
660
0
    }
661
0
    if (depTgt->GetPropertyAsBool("IMPORTED_NO_SYSTEM")) {
662
0
      return;
663
0
    }
664
0
  }
665
666
0
  if (cmValue dirs = depTgt->GetProperty("INTERFACE_INCLUDE_DIRECTORIES")) {
667
0
    result.append(cmGeneratorExpression::Evaluate(
668
0
      *dirs, lg, config, headTarget, dagChecker, depTgt, language));
669
0
  }
670
671
0
  if (depTgt->Target->IsFrameworkOnApple() ||
672
0
      depTgt->IsImportedFrameworkFolderOnApple(config)) {
673
0
    if (auto fwDescriptor = depTgt->GetGlobalGenerator()->SplitFrameworkPath(
674
0
          depTgt->GetLocation(config))) {
675
0
      result.push_back(fwDescriptor->Directory);
676
0
      result.push_back(fwDescriptor->GetFrameworkPath());
677
0
    }
678
0
  }
679
0
}
680
}
681
682
/* clang-format off */
683
#define IMPLEMENT_VISIT(KIND)                                                 \
684
0
  do {                                                                        \
685
0
    KindedSources const& kinded = this->GetKindedSources(config);             \
686
0
    for (SourceAndKind const& s : kinded.Sources) {                           \
687
0
      if (s.Kind == KIND) {                                                   \
688
0
        data.push_back(s.Source.Value);                                       \
689
0
      }                                                                       \
690
0
    }                                                                         \
691
0
  } while (false)
692
/* clang-format on */
693
694
void cmGeneratorTarget::GetObjectSources(
695
  std::vector<cmSourceFile const*>& data, std::string const& config) const
696
0
{
697
0
  IMPLEMENT_VISIT(SourceKindObjectSource);
698
699
0
  if (this->VisitedConfigsForObjects.count(config)) {
700
0
    return;
701
0
  }
702
703
0
  for (cmSourceFile const* it : data) {
704
0
    this->Objects[it];
705
0
  }
706
707
0
  this->LocalGenerator->ComputeObjectFilenames(this->Objects, config, this);
708
0
  this->VisitedConfigsForObjects.insert(config);
709
0
}
710
711
void cmGeneratorTarget::ComputeObjectMapping()
712
0
{
713
0
  auto const& configs =
714
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
715
0
  std::set<std::string> configSet(configs.begin(), configs.end());
716
0
  if (configSet == this->VisitedConfigsForObjects) {
717
0
    return;
718
0
  }
719
720
0
  for (std::string const& c : configs) {
721
0
    std::vector<cmSourceFile const*> sourceFiles;
722
0
    this->GetObjectSources(sourceFiles, c);
723
0
  }
724
0
}
725
726
cmValue cmGeneratorTarget::GetFeature(std::string const& feature,
727
                                      std::string const& config) const
728
0
{
729
0
  if (!config.empty()) {
730
0
    std::string featureConfig =
731
0
      cmStrCat(feature, '_', cmSystemTools::UpperCase(config));
732
0
    if (cmValue value = this->GetProperty(featureConfig)) {
733
0
      return value;
734
0
    }
735
0
  }
736
0
  if (cmValue value = this->GetProperty(feature)) {
737
0
    return value;
738
0
  }
739
0
  return this->LocalGenerator->GetFeature(feature, config);
740
0
}
741
742
std::string cmGeneratorTarget::GetLinkerTypeProperty(
743
  std::string const& lang, std::string const& config) const
744
0
{
745
0
  std::string propName{ "LINKER_TYPE" };
746
0
  auto linkerType = this->GetProperty(propName);
747
0
  if (!linkerType.IsEmpty()) {
748
0
    cm::GenEx::Context context(this->LocalGenerator, config, lang);
749
0
    cmGeneratorExpressionDAGChecker dagChecker{
750
0
      this, propName, nullptr, nullptr, context,
751
0
    };
752
0
    auto ltype = cmGeneratorExpression::Evaluate(
753
0
      *linkerType, context.LG, context.Config, this, &dagChecker, this,
754
0
      context.Language);
755
0
    if (this->IsDeviceLink()) {
756
0
      cmList list{ ltype };
757
0
      auto const DL_BEGIN = "<DEVICE_LINK>"_s;
758
0
      auto const DL_END = "</DEVICE_LINK>"_s;
759
0
      cm::erase_if(list, [&](std::string const& item) {
760
0
        return item == DL_BEGIN || item == DL_END;
761
0
      });
762
0
      return list.to_string();
763
0
    }
764
0
    return ltype;
765
0
  }
766
0
  return std::string{};
767
0
}
768
769
char const* cmGeneratorTarget::GetLinkPIEProperty(
770
  std::string const& config) const
771
0
{
772
0
  static std::string PICValue;
773
774
0
  PICValue = this->GetLinkInterfaceDependentStringAsBoolProperty(
775
0
    "POSITION_INDEPENDENT_CODE", config);
776
777
0
  if (PICValue == "(unset)") {
778
    // POSITION_INDEPENDENT_CODE is not set
779
0
    return nullptr;
780
0
  }
781
782
0
  auto status = this->GetPolicyStatusCMP0083();
783
0
  return (status != cmPolicies::WARN && status != cmPolicies::OLD)
784
0
    ? PICValue.c_str()
785
0
    : nullptr;
786
0
}
787
788
bool cmGeneratorTarget::IsIPOEnabled(std::string const& lang,
789
                                     std::string const& config) const
790
0
{
791
0
  cmValue feature = this->GetFeature("INTERPROCEDURAL_OPTIMIZATION", config);
792
793
0
  if (!feature.IsOn()) {
794
    // 'INTERPROCEDURAL_OPTIMIZATION' is off, no need to check policies
795
0
    return false;
796
0
  }
797
798
0
  if (lang != "C" && lang != "CXX" && lang != "CUDA" && lang != "Fortran") {
799
    // We do not define IPO behavior for other languages.
800
0
    return false;
801
0
  }
802
803
0
  if (lang == "CUDA") {
804
    // CUDA IPO requires both CUDA_ARCHITECTURES and CUDA_SEPARABLE_COMPILATION
805
0
    if (cmIsOff(this->GetSafeProperty("CUDA_ARCHITECTURES")) ||
806
0
        cmIsOff(this->GetSafeProperty("CUDA_SEPARABLE_COMPILATION"))) {
807
0
      return false;
808
0
    }
809
0
  }
810
811
0
  cmPolicies::PolicyStatus cmp0069 = this->GetPolicyStatusCMP0069();
812
813
0
  if (cmp0069 == cmPolicies::OLD || cmp0069 == cmPolicies::WARN) {
814
0
    if (this->Makefile->IsOn(
815
0
          cmStrCat("_CMAKE_", lang, "_IPO_LEGACY_BEHAVIOR"))) {
816
0
      return true;
817
0
    }
818
0
    if (this->PolicyReportedCMP0069) {
819
      // problem is already reported, no need to issue a message
820
0
      return false;
821
0
    }
822
0
    bool const in_try_compile =
823
0
      this->LocalGenerator->GetCMakeInstance()->GetIsInTryCompile();
824
0
    if (cmp0069 == cmPolicies::WARN && !in_try_compile) {
825
0
      this->Makefile->IssuePolicyWarning(
826
0
        cmPolicies::CMP0069, {},
827
0
        cmStrCat("INTERPROCEDURAL_OPTIMIZATION property "
828
0
                 "will be ignored for target '"_s,
829
0
                 this->GetName(), "'."_s),
830
0
        this->GetBacktrace());
831
832
0
      this->PolicyReportedCMP0069 = true;
833
0
    }
834
0
    return false;
835
0
  }
836
837
  // Note: check consistency with messages from CheckIPOSupported
838
0
  char const* message = nullptr;
839
0
  if (!this->Makefile->IsOn(
840
0
        cmStrCat("_CMAKE_", lang, "_IPO_SUPPORTED_BY_CMAKE"))) {
841
0
    message = "CMake doesn't support IPO for current compiler";
842
0
  } else if (!this->Makefile->IsOn(cmStrCat(
843
0
               "_CMAKE_", lang, "_IPO_MAY_BE_SUPPORTED_BY_COMPILER"))) {
844
0
    message = "Compiler doesn't support IPO";
845
0
  } else if (!this->GlobalGenerator->IsIPOSupported()) {
846
0
    message = "CMake doesn't support IPO for current generator";
847
0
  }
848
849
0
  if (!message) {
850
    // No error/warning messages
851
0
    return true;
852
0
  }
853
854
0
  if (this->PolicyReportedCMP0069) {
855
    // problem is already reported, no need to issue a message
856
0
    return false;
857
0
  }
858
859
0
  this->PolicyReportedCMP0069 = true;
860
861
0
  this->LocalGenerator->GetCMakeInstance()->IssueMessage(
862
0
    MessageType::FATAL_ERROR, message, this->GetBacktrace());
863
0
  return false;
864
0
}
865
866
std::string const& cmGeneratorTarget::GetObjectName(cmSourceFile const* file)
867
0
{
868
0
  this->ComputeObjectMapping();
869
0
  auto const useShortPaths = this->GetUseShortObjectNames()
870
0
    ? cmObjectLocations::UseShortPath::Yes
871
0
    : cmObjectLocations::UseShortPath::No;
872
0
  return this->Objects[file].GetPath(useShortPaths);
873
0
}
874
875
char const* cmGeneratorTarget::GetCustomObjectExtension() const
876
0
{
877
0
  struct compiler_mode
878
0
  {
879
0
    std::string variable;
880
0
    std::string extension;
881
0
  };
882
0
  static std::array<compiler_mode, 4> const modes{
883
0
    { { "CUDA_PTX_COMPILATION", ".ptx" },
884
0
      { "CUDA_CUBIN_COMPILATION", ".cubin" },
885
0
      { "CUDA_FATBIN_COMPILATION", ".fatbin" },
886
0
      { "CUDA_OPTIX_COMPILATION", ".optixir" } }
887
0
  };
888
889
0
  std::string const& compiler =
890
0
    this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID");
891
0
  if (!compiler.empty()) {
892
0
    for (auto const& m : modes) {
893
0
      bool const has_extension = this->GetPropertyAsBool(m.variable);
894
0
      if (has_extension) {
895
0
        return m.extension.c_str();
896
0
      }
897
0
    }
898
0
  }
899
0
  return nullptr;
900
0
}
901
902
void cmGeneratorTarget::AddExplicitObjectName(cmSourceFile const* sf)
903
0
{
904
0
  this->ExplicitObjectName.insert(sf);
905
0
}
906
907
bool cmGeneratorTarget::HasExplicitObjectName(cmSourceFile const* file) const
908
0
{
909
0
  const_cast<cmGeneratorTarget*>(this)->ComputeObjectMapping();
910
0
  auto it = this->ExplicitObjectName.find(file);
911
0
  return it != this->ExplicitObjectName.end();
912
0
}
913
914
BTs<std::string> const* cmGeneratorTarget::GetLanguageStandardProperty(
915
  std::string const& lang, std::string const& config) const
916
0
{
917
0
  std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
918
0
  auto langStandardIter = this->LanguageStandardMap.find(key);
919
0
  if (langStandardIter != this->LanguageStandardMap.end()) {
920
0
    return &langStandardIter->second;
921
0
  }
922
923
0
  return this->Target->GetLanguageStandardProperty(
924
0
    cmStrCat(lang, "_STANDARD"));
925
0
}
926
927
cmValue cmGeneratorTarget::GetLanguageStandard(std::string const& lang,
928
                                               std::string const& config) const
929
0
{
930
0
  BTs<std::string> const* languageStandard =
931
0
    this->GetLanguageStandardProperty(lang, config);
932
933
0
  if (languageStandard) {
934
0
    return cmValue(languageStandard->Value);
935
0
  }
936
937
0
  return nullptr;
938
0
}
939
940
cmValue cmGeneratorTarget::GetPropertyWithPairedLanguageSupport(
941
  std::string const& lang, char const* suffix) const
942
0
{
943
0
  cmValue propertyValue = this->Target->GetProperty(cmStrCat(lang, suffix));
944
0
  if (!propertyValue) {
945
    // Check if we should use the value set by another language.
946
0
    if (lang == "OBJC") {
947
0
      propertyValue = this->GetPropertyWithPairedLanguageSupport("C", suffix);
948
0
    } else if (lang == "OBJCXX" || lang == "CUDA" || lang == "HIP") {
949
0
      propertyValue =
950
0
        this->GetPropertyWithPairedLanguageSupport("CXX", suffix);
951
0
    }
952
0
  }
953
0
  return propertyValue;
954
0
}
955
956
cmValue cmGeneratorTarget::GetLanguageExtensions(std::string const& lang) const
957
0
{
958
0
  return this->GetPropertyWithPairedLanguageSupport(lang, "_EXTENSIONS");
959
0
}
960
961
bool cmGeneratorTarget::GetLanguageStandardRequired(
962
  std::string const& lang) const
963
0
{
964
0
  return this->GetPropertyWithPairedLanguageSupport(lang, "_STANDARD_REQUIRED")
965
0
    .IsOn();
966
0
}
967
968
void cmGeneratorTarget::GetModuleDefinitionSources(
969
  std::vector<cmSourceFile const*>& data, std::string const& config) const
970
0
{
971
0
  IMPLEMENT_VISIT(SourceKindModuleDefinition);
972
0
}
973
974
void cmGeneratorTarget::GetHeaderSources(
975
  std::vector<cmSourceFile const*>& data, std::string const& config) const
976
0
{
977
0
  IMPLEMENT_VISIT(SourceKindHeader);
978
0
}
979
980
void cmGeneratorTarget::GetCxxModuleSources(
981
  std::vector<cmSourceFile const*>& data, std::string const& config) const
982
0
{
983
0
  IMPLEMENT_VISIT(SourceKindCxxModuleSource);
984
0
}
985
986
void cmGeneratorTarget::GetExtraSources(std::vector<cmSourceFile const*>& data,
987
                                        std::string const& config) const
988
0
{
989
0
  IMPLEMENT_VISIT(SourceKindExtra);
990
0
}
991
992
void cmGeneratorTarget::GetCustomCommands(
993
  std::vector<cmSourceFile const*>& data, std::string const& config) const
994
0
{
995
0
  IMPLEMENT_VISIT(SourceKindCustomCommand);
996
0
}
997
998
void cmGeneratorTarget::GetExternalObjects(
999
  std::vector<cmSourceFile const*>& data, std::string const& config) const
1000
0
{
1001
0
  IMPLEMENT_VISIT(SourceKindExternalObject);
1002
0
}
1003
1004
void cmGeneratorTarget::GetManifests(std::vector<cmSourceFile const*>& data,
1005
                                     std::string const& config) const
1006
0
{
1007
0
  IMPLEMENT_VISIT(SourceKindManifest);
1008
0
}
1009
1010
void cmGeneratorTarget::GetRustMainCrateRoot(
1011
  std::vector<cmSourceFile const*>& data, std::string const& config) const
1012
0
{
1013
0
  IMPLEMENT_VISIT(SourceKindRustMainCrateRoot);
1014
0
}
1015
1016
cmSourceFile const* cmGeneratorTarget::GetRustMainCrateRoot(
1017
  std::string const& config) const
1018
0
{
1019
0
  std::vector<cmSourceFile const*> files;
1020
0
  GetRustMainCrateRoot(files, config);
1021
0
  if (files.empty()) {
1022
0
    return nullptr;
1023
0
  }
1024
0
  assert(files.size() == 1);
1025
0
  return files[0];
1026
0
}
1027
1028
std::set<cmLinkItem> const& cmGeneratorTarget::GetUtilityItems() const
1029
0
{
1030
0
  if (!this->UtilityItemsDone) {
1031
0
    this->UtilityItemsDone = true;
1032
0
    std::set<BT<std::pair<std::string, bool>>> const& utilities =
1033
0
      this->GetUtilities();
1034
0
    for (BT<std::pair<std::string, bool>> const& i : utilities) {
1035
0
      if (cmGeneratorTarget* gt =
1036
0
            this->LocalGenerator->FindGeneratorTargetToUse(i.Value.first)) {
1037
0
        this->UtilityItems.insert(cmLinkItem(gt, i.Value.second, i.Backtrace));
1038
0
      } else {
1039
0
        this->UtilityItems.insert(
1040
0
          cmLinkItem(i.Value.first, i.Value.second, i.Backtrace));
1041
0
      }
1042
0
    }
1043
0
    if (cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget()) {
1044
0
      this->UtilityItems.insert(
1045
0
        cmLinkItem(reuseTarget, false, cmListFileBacktrace()));
1046
0
    }
1047
0
  }
1048
0
  return this->UtilityItems;
1049
0
}
1050
1051
std::string const& cmGeneratorTarget::GetLocation(
1052
  std::string const& config) const
1053
0
{
1054
0
  static std::string location;
1055
0
  if (this->IsImported()) {
1056
0
    location = this->Target->ImportedGetFullPath(
1057
0
      config, cmStateEnums::RuntimeBinaryArtifact);
1058
0
  } else {
1059
0
    location = this->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact);
1060
0
  }
1061
0
  return location;
1062
0
}
1063
1064
cm::optional<std::string> cmGeneratorTarget::MaybeGetLocation(
1065
  std::string const& config) const
1066
0
{
1067
0
  cm::optional<std::string> location;
1068
0
  if (cmGeneratorTarget::ImportInfo const* imp = this->GetImportInfo(config)) {
1069
0
    if (!imp->Location.empty()) {
1070
0
      location = imp->Location;
1071
0
    }
1072
0
  } else {
1073
0
    location = this->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact);
1074
0
  }
1075
0
  return location;
1076
0
}
1077
1078
std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPreBuildCommands()
1079
  const
1080
0
{
1081
0
  return this->Target->GetPreBuildCommands();
1082
0
}
1083
1084
std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPreLinkCommands()
1085
  const
1086
0
{
1087
0
  return this->Target->GetPreLinkCommands();
1088
0
}
1089
1090
std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPostBuildCommands()
1091
  const
1092
0
{
1093
0
  return this->Target->GetPostBuildCommands();
1094
0
}
1095
1096
void cmGeneratorTarget::AppendCustomCommandSideEffects(
1097
  std::set<cmGeneratorTarget const*>& sideEffects) const
1098
0
{
1099
0
  if (!this->GetPreBuildCommands().empty() ||
1100
0
      !this->GetPreLinkCommands().empty() ||
1101
0
      !this->GetPostBuildCommands().empty()) {
1102
0
    sideEffects.insert(this);
1103
0
  } else {
1104
0
    for (auto const& source : this->GetAllConfigSources()) {
1105
0
      if (source.Source->GetCustomCommand()) {
1106
0
        sideEffects.insert(this);
1107
0
        break;
1108
0
      }
1109
0
    }
1110
0
  }
1111
0
}
1112
1113
void cmGeneratorTarget::AppendLanguageSideEffects(
1114
  std::map<std::string, std::set<cmGeneratorTarget const*>>& sideEffects) const
1115
0
{
1116
0
  static std::set<cm::string_view> const LANGS_WITH_NO_SIDE_EFFECTS = {
1117
0
    "C"_s, "CXX"_s, "OBJC"_s, "OBJCXX"_s, "ASM"_s, "CUDA"_s, "HIP"_s
1118
0
  };
1119
1120
0
  for (auto const& lang : this->GetAllConfigCompileLanguages()) {
1121
0
    if (!LANGS_WITH_NO_SIDE_EFFECTS.count(lang)) {
1122
0
      sideEffects[lang].insert(this);
1123
0
    }
1124
0
  }
1125
0
}
1126
1127
bool cmGeneratorTarget::IsInBuildSystem() const
1128
0
{
1129
0
  if (this->IsImported()) {
1130
0
    return false;
1131
0
  }
1132
0
  switch (this->Target->GetType()) {
1133
0
    case cm::TargetType::EXECUTABLE:
1134
0
    case cm::TargetType::STATIC_LIBRARY:
1135
0
    case cm::TargetType::SHARED_LIBRARY:
1136
0
    case cm::TargetType::MODULE_LIBRARY:
1137
0
    case cm::TargetType::OBJECT_LIBRARY:
1138
0
    case cm::TargetType::UTILITY:
1139
0
    case cm::TargetType::GLOBAL_TARGET:
1140
0
      return true;
1141
0
    case cm::TargetType::INTERFACE_LIBRARY:
1142
      // An INTERFACE library is in the build system if it has SOURCES
1143
      // or C++ module filesets.
1144
0
      if (!this->SourceEntries.empty() ||
1145
0
          !this->GetFileSets(cm::FileSetMetadata::HEADERS).empty() ||
1146
0
          !this->GetFileSets(cm::FileSetMetadata::CXX_MODULES).empty()) {
1147
0
        return true;
1148
0
      }
1149
0
      break;
1150
0
    case cm::TargetType::UNKNOWN_LIBRARY:
1151
0
      break;
1152
0
  }
1153
0
  return false;
1154
0
}
1155
1156
bool cmGeneratorTarget::IsNormal() const
1157
0
{
1158
0
  return this->Target->IsNormal();
1159
0
}
1160
1161
bool cmGeneratorTarget::IsRuntimeBinary() const
1162
0
{
1163
0
  return this->Target->IsRuntimeBinary();
1164
0
}
1165
1166
bool cmGeneratorTarget::IsSynthetic() const
1167
0
{
1168
0
  return this->Target->IsSynthetic();
1169
0
}
1170
1171
bool cmGeneratorTarget::IsImported() const
1172
0
{
1173
0
  return this->Target->IsImported();
1174
0
}
1175
1176
bool cmGeneratorTarget::IsImportedGloballyVisible() const
1177
0
{
1178
0
  return this->Target->IsImportedGloballyVisible();
1179
0
}
1180
1181
bool cmGeneratorTarget::IsSymbolic() const
1182
0
{
1183
0
  return this->Target->IsSymbolic();
1184
0
}
1185
1186
bool cmGeneratorTarget::IsForeign() const
1187
0
{
1188
0
  return this->Target->IsForeign();
1189
0
}
1190
1191
bool cmGeneratorTarget::CanCompileSources() const
1192
0
{
1193
0
  return this->Target->CanCompileSources();
1194
0
}
1195
1196
bool cmGeneratorTarget::HasKnownRuntimeArtifactLocation(
1197
  std::string const& config) const
1198
0
{
1199
0
  if (!this->IsRuntimeBinary()) {
1200
0
    return false;
1201
0
  }
1202
0
  if (!this->IsImported()) {
1203
0
    return true;
1204
0
  }
1205
0
  ImportInfo const* info = this->GetImportInfo(config);
1206
0
  return info && !info->Location.empty();
1207
0
}
1208
1209
std::string const& cmGeneratorTarget::GetLocationForBuild() const
1210
0
{
1211
0
  static std::string location;
1212
0
  if (this->IsImported()) {
1213
0
    location = this->Target->ImportedGetFullPath(
1214
0
      "", cmStateEnums::RuntimeBinaryArtifact);
1215
0
    return location;
1216
0
  }
1217
1218
  // Now handle the deprecated build-time configuration location.
1219
0
  std::string const noConfig;
1220
0
  location = this->GetDirectory(noConfig);
1221
0
  cmValue cfgid = this->Makefile->GetDefinition("CMAKE_CFG_INTDIR");
1222
0
  if (cfgid && (*cfgid != ".")) {
1223
0
    location = cmStrCat(std::move(location), '/', *cfgid);
1224
0
  }
1225
1226
0
  if (this->IsAppBundleOnApple()) {
1227
0
    std::string macdir = this->BuildBundleDirectory("", "", FullLevel);
1228
0
    if (!macdir.empty()) {
1229
0
      location = cmStrCat(std::move(location), '/', macdir);
1230
0
    }
1231
0
  }
1232
0
  location =
1233
0
    cmStrCat(std::move(location), '/',
1234
0
             this->GetFullName("", cmStateEnums::RuntimeBinaryArtifact));
1235
0
  return location;
1236
0
}
1237
1238
void cmGeneratorTarget::AddSystemIncludeCacheKey(
1239
  std::string const& key, std::string const& config,
1240
  std::string const& language) const
1241
0
{
1242
0
  cm::GenEx::Context context(this->LocalGenerator, config, language);
1243
0
  cmGeneratorExpressionDAGChecker dagChecker{
1244
0
    this, "SYSTEM_INCLUDE_DIRECTORIES", nullptr, nullptr, context,
1245
0
  };
1246
1247
0
  bool excludeImported = this->GetPropertyAsBool("NO_SYSTEM_FROM_IMPORTED");
1248
1249
0
  cmList result;
1250
0
  for (std::string const& it : this->Target->GetSystemIncludeDirectories()) {
1251
0
    result.append(
1252
0
      cmGeneratorExpression::Evaluate(it, context.LG, context.Config, this,
1253
0
                                      &dagChecker, nullptr, context.Language));
1254
0
  }
1255
1256
0
  std::vector<cmGeneratorTarget const*> const& deps =
1257
0
    this->GetLinkImplementationClosure(config, UseTo::Compile);
1258
0
  for (cmGeneratorTarget const* dep : deps) {
1259
0
    handleSystemIncludesDep(context.LG, dep, context.Config, this, &dagChecker,
1260
0
                            result, excludeImported, context.Language);
1261
0
  }
1262
1263
0
  cmLinkImplementation const* impl =
1264
0
    this->GetLinkImplementation(config, UseTo::Compile);
1265
0
  if (impl) {
1266
0
    auto runtimeEntries = impl->LanguageRuntimeLibraries.find(language);
1267
0
    if (runtimeEntries != impl->LanguageRuntimeLibraries.end()) {
1268
0
      for (auto const& lib : runtimeEntries->second) {
1269
0
        if (lib.Target) {
1270
0
          handleSystemIncludesDep(context.LG, lib.Target, context.Config, this,
1271
0
                                  &dagChecker, result, excludeImported,
1272
0
                                  context.Language);
1273
0
        }
1274
0
      }
1275
0
    }
1276
0
  }
1277
1278
0
  std::for_each(result.begin(), result.end(),
1279
0
                cmSystemTools::ConvertToUnixSlashes);
1280
0
  std::sort(result.begin(), result.end());
1281
0
  result.erase(std::unique(result.begin(), result.end()), result.end());
1282
0
  SystemIncludesCache.emplace(key, result);
1283
0
}
1284
1285
bool cmGeneratorTarget::IsSystemIncludeDirectory(
1286
  std::string const& dir, std::string const& config,
1287
  std::string const& language) const
1288
0
{
1289
0
  std::string config_upper;
1290
0
  if (!config.empty()) {
1291
0
    config_upper = cmSystemTools::UpperCase(config);
1292
0
  }
1293
1294
0
  std::string key = cmStrCat(config_upper, '/', language);
1295
0
  auto iter = this->SystemIncludesCache.find(key);
1296
1297
0
  if (iter == this->SystemIncludesCache.end()) {
1298
0
    this->AddSystemIncludeCacheKey(key, config, language);
1299
0
    iter = this->SystemIncludesCache.find(key);
1300
0
  }
1301
1302
0
  return std::binary_search(iter->second.begin(), iter->second.end(), dir);
1303
0
}
1304
1305
bool cmGeneratorTarget::GetPropertyAsBool(std::string const& prop) const
1306
0
{
1307
0
  return this->Target->GetPropertyAsBool(prop);
1308
0
}
1309
1310
std::string cmGeneratorTarget::GetCompilePDBName(
1311
  std::string const& config) const
1312
0
{
1313
0
  if (cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget()) {
1314
0
    if (reuseTarget != this) {
1315
0
      return reuseTarget->GetCompilePDBName(config);
1316
0
    }
1317
0
  }
1318
1319
  // Check for a per-configuration output directory target property.
1320
0
  std::string configUpper = cmSystemTools::UpperCase(config);
1321
0
  std::string configProp = cmStrCat("COMPILE_PDB_NAME_", configUpper);
1322
0
  cmValue config_name = this->GetProperty(configProp);
1323
0
  if (cmNonempty(config_name)) {
1324
0
    std::string pdbName = cmGeneratorExpression::Evaluate(
1325
0
      *config_name, this->LocalGenerator, config, this);
1326
0
    NameComponents const& components = GetFullNameInternalComponents(
1327
0
      config, cmStateEnums::RuntimeBinaryArtifact);
1328
0
    return components.prefix + pdbName + ".pdb";
1329
0
  }
1330
1331
0
  cmValue name = this->GetProperty("COMPILE_PDB_NAME");
1332
0
  if (cmNonempty(name)) {
1333
0
    std::string pdbName = cmGeneratorExpression::Evaluate(
1334
0
      *name, this->LocalGenerator, config, this);
1335
0
    NameComponents const& components = GetFullNameInternalComponents(
1336
0
      config, cmStateEnums::RuntimeBinaryArtifact);
1337
0
    return components.prefix + pdbName + ".pdb";
1338
0
  }
1339
1340
  // If the target is PCH-reused or PCH-reuses, we need a stable name for the
1341
  // PDB file so that reusing targets can construct a stable name for it.
1342
0
  cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget();
1343
0
  bool const hasReuse = reuseTarget && reuseTarget != this;
1344
0
  if (this->PchReused || hasReuse) {
1345
0
    NameComponents const& components = GetFullNameInternalComponents(
1346
0
      config, cmStateEnums::RuntimeBinaryArtifact);
1347
0
    return cmStrCat(components.prefix, this->GetName(), ".pdb");
1348
0
  }
1349
1350
0
  return std::string{};
1351
0
}
1352
1353
std::string cmGeneratorTarget::GetCompilePDBPath(
1354
  std::string const& config) const
1355
0
{
1356
0
  std::string dir = this->GetCompilePDBDirectory(config);
1357
0
  std::string name = this->GetCompilePDBName(config);
1358
0
  if (dir.empty() && !name.empty() && this->HaveWellDefinedOutputFiles()) {
1359
0
    dir = this->GetPDBDirectory(config);
1360
0
  }
1361
0
  if (!dir.empty()) {
1362
0
    dir += '/';
1363
0
  }
1364
0
  return dir + name;
1365
0
}
1366
1367
bool cmGeneratorTarget::HasSOName(std::string const& config) const
1368
0
{
1369
  // soname is supported only for shared libraries and modules,
1370
  // and then only when the platform supports an soname flag.
1371
0
  return ((this->GetType() == cm::TargetType::SHARED_LIBRARY) &&
1372
0
          !this->GetPropertyAsBool("NO_SONAME") &&
1373
0
          (this->Makefile->GetSONameFlag(this->GetLinkerLanguage(config)) ||
1374
0
           this->IsArchivedAIXSharedLibrary()));
1375
0
}
1376
1377
bool cmGeneratorTarget::NeedRelinkBeforeInstall(
1378
  std::string const& config) const
1379
0
{
1380
  // Only executables and shared libraries can have an rpath and may
1381
  // need relinking.
1382
0
  if (this->GetType() != cm::TargetType::EXECUTABLE &&
1383
0
      this->GetType() != cm::TargetType::SHARED_LIBRARY &&
1384
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY) {
1385
0
    return false;
1386
0
  }
1387
1388
  // If there is no install location this target will not be installed
1389
  // and therefore does not need relinking.
1390
0
  if (!this->Target->GetHaveInstallRule()) {
1391
0
    return false;
1392
0
  }
1393
1394
  // If skipping all rpaths completely then no relinking is needed.
1395
0
  if (this->Makefile->IsOn("CMAKE_SKIP_RPATH")) {
1396
0
    return false;
1397
0
  }
1398
1399
  // If building with the install-tree rpath no relinking is needed.
1400
0
  if (this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH")) {
1401
0
    return false;
1402
0
  }
1403
1404
  // If chrpath is going to be used no relinking is needed.
1405
0
  if (this->IsChrpathUsed(config)) {
1406
0
    return false;
1407
0
  }
1408
1409
  // Check for rpath support on this platform.
1410
0
  std::string ll = this->GetLinkerLanguage(config);
1411
0
  if (!ll.empty()) {
1412
0
    std::string flagVar =
1413
0
      cmStrCat("CMAKE_SHARED_LIBRARY_RUNTIME_", ll, "_FLAG");
1414
0
    if (!this->Makefile->IsSet(flagVar)) {
1415
      // There is no rpath support on this platform so nothing needs
1416
      // relinking.
1417
0
      return false;
1418
0
    }
1419
0
  } else {
1420
    // No linker language is known.  This error will be reported by
1421
    // other code.
1422
0
    return false;
1423
0
  }
1424
1425
  // If either a build or install tree rpath is set then the rpath
1426
  // will likely change between the build tree and install tree and
1427
  // this target must be relinked.
1428
0
  bool have_rpath =
1429
0
    this->HaveBuildTreeRPATH(config) || this->HaveInstallTreeRPATH(config);
1430
0
  bool is_ninja = this->LocalGenerator->GetGlobalGenerator()->IsNinja();
1431
1432
0
  if (have_rpath && is_ninja) {
1433
0
    std::ostringstream w;
1434
    /* clang-format off */
1435
0
    w <<
1436
0
      "The install of the " << this->GetName() << " target requires changing "
1437
0
      "an RPATH from the build tree, but this is not supported with the Ninja "
1438
0
      "generator unless on an ELF-based or XCOFF-based platform.  "
1439
0
      "The CMAKE_BUILD_WITH_INSTALL_RPATH variable may be set to avoid this "
1440
0
      "relinking step."
1441
0
      ;
1442
    /* clang-format on */
1443
1444
0
    cmake* cm = this->LocalGenerator->GetCMakeInstance();
1445
0
    cm->IssueMessage(MessageType::FATAL_ERROR, w.str(), this->GetBacktrace());
1446
0
  }
1447
1448
0
  return have_rpath;
1449
0
}
1450
1451
bool cmGeneratorTarget::IsChrpathUsed(std::string const& config) const
1452
0
{
1453
  // Only certain target types have an rpath.
1454
0
  if (!(this->GetType() == cm::TargetType::SHARED_LIBRARY ||
1455
0
        this->GetType() == cm::TargetType::MODULE_LIBRARY ||
1456
0
        this->GetType() == cm::TargetType::EXECUTABLE)) {
1457
0
    return false;
1458
0
  }
1459
1460
  // If the target will not be installed we do not need to change its
1461
  // rpath.
1462
0
  if (!this->Target->GetHaveInstallRule()) {
1463
0
    return false;
1464
0
  }
1465
1466
  // Skip chrpath if skipping rpath altogether.
1467
0
  if (this->Makefile->IsOn("CMAKE_SKIP_RPATH")) {
1468
0
    return false;
1469
0
  }
1470
1471
  // Skip chrpath if it does not need to be changed at install time.
1472
0
  if (this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH")) {
1473
0
    return false;
1474
0
  }
1475
1476
  // Allow the user to disable builtin chrpath explicitly.
1477
0
  if (this->Makefile->IsOn("CMAKE_NO_BUILTIN_CHRPATH")) {
1478
0
    return false;
1479
0
  }
1480
1481
0
  if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
1482
0
    return true;
1483
0
  }
1484
1485
  // Enable if the rpath flag uses a separator and the target uses
1486
  // binaries we know how to edit.
1487
0
  std::string ll = this->GetLinkerLanguage(config);
1488
0
  if (!ll.empty()) {
1489
0
    std::string sepVar =
1490
0
      cmStrCat("CMAKE_SHARED_LIBRARY_RUNTIME_", ll, "_FLAG_SEP");
1491
0
    cmValue sep = this->Makefile->GetDefinition(sepVar);
1492
0
    if (cmNonempty(sep)) {
1493
      // TODO: Add binary format check to ABI detection and get rid of
1494
      // CMAKE_EXECUTABLE_FORMAT.
1495
0
      if (cmValue fmt =
1496
0
            this->Makefile->GetDefinition("CMAKE_EXECUTABLE_FORMAT")) {
1497
0
        if (*fmt == "ELF") {
1498
0
          return true;
1499
0
        }
1500
#if defined(CMake_USE_XCOFF_PARSER)
1501
        if (*fmt == "XCOFF") {
1502
          return true;
1503
        }
1504
#endif
1505
0
      }
1506
0
    }
1507
0
  }
1508
0
  return false;
1509
0
}
1510
1511
bool cmGeneratorTarget::IsImportedSharedLibWithoutSOName(
1512
  std::string const& config) const
1513
0
{
1514
0
  if (this->IsImported() &&
1515
0
      this->GetType() == cm::TargetType::SHARED_LIBRARY) {
1516
0
    if (cmGeneratorTarget::ImportInfo const* info =
1517
0
          this->GetImportInfo(config)) {
1518
0
      return info->NoSOName;
1519
0
    }
1520
0
  }
1521
0
  return false;
1522
0
}
1523
1524
bool cmGeneratorTarget::HasMacOSXRpathInstallNameDir(
1525
  std::string const& config) const
1526
0
{
1527
0
  TargetPtrToBoolMap& cache = this->MacOSXRpathInstallNameDirCache[config];
1528
0
  auto const lookup = cache.find(this->Target);
1529
1530
0
  if (lookup != cache.cend()) {
1531
0
    return lookup->second;
1532
0
  }
1533
1534
0
  bool const result = this->DetermineHasMacOSXRpathInstallNameDir(config);
1535
0
  cache[this->Target] = result;
1536
0
  return result;
1537
0
}
1538
1539
bool cmGeneratorTarget::DetermineHasMacOSXRpathInstallNameDir(
1540
  std::string const& config) const
1541
0
{
1542
0
  bool install_name_is_rpath = false;
1543
0
  bool macosx_rpath = false;
1544
1545
0
  if (!this->IsImported()) {
1546
0
    if (this->GetType() != cm::TargetType::SHARED_LIBRARY) {
1547
0
      return false;
1548
0
    }
1549
0
    cmValue install_name = this->GetProperty("INSTALL_NAME_DIR");
1550
0
    bool use_install_name = this->MacOSXUseInstallNameDir();
1551
0
    if (install_name && use_install_name && *install_name == "@rpath") {
1552
0
      install_name_is_rpath = true;
1553
0
    } else if (install_name && use_install_name) {
1554
0
      return false;
1555
0
    }
1556
0
    if (!install_name_is_rpath) {
1557
0
      macosx_rpath = this->MacOSXRpathInstallNameDirDefault();
1558
0
    }
1559
0
  } else {
1560
    // Lookup the imported soname.
1561
0
    if (cmGeneratorTarget::ImportInfo const* info =
1562
0
          this->GetImportInfo(config)) {
1563
0
      if (!info->NoSOName && !info->SOName.empty()) {
1564
0
        if (cmHasLiteralPrefix(info->SOName, "@rpath/")) {
1565
0
          install_name_is_rpath = true;
1566
0
        }
1567
0
      } else {
1568
0
        std::string install_name;
1569
0
        cmSystemTools::GuessLibraryInstallName(info->Location, install_name);
1570
0
        if (install_name.find("@rpath") != std::string::npos) {
1571
0
          install_name_is_rpath = true;
1572
0
        }
1573
0
      }
1574
0
    }
1575
0
  }
1576
1577
0
  if (!install_name_is_rpath && !macosx_rpath) {
1578
0
    return false;
1579
0
  }
1580
1581
0
  if (!this->Makefile->IsSet("CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG")) {
1582
0
    std::ostringstream w;
1583
0
    w << "Attempting to use ";
1584
0
    if (macosx_rpath) {
1585
0
      w << "MACOSX_RPATH";
1586
0
    } else {
1587
0
      w << "@rpath";
1588
0
    }
1589
0
    w << " without CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG being set.";
1590
0
    w << "  This could be because you are using a Mac OS X version";
1591
0
    w << " less than 10.5 or because CMake's platform configuration is";
1592
0
    w << " corrupt.";
1593
0
    cmake* cm = this->LocalGenerator->GetCMakeInstance();
1594
0
    cm->IssueMessage(MessageType::FATAL_ERROR, w.str(), this->GetBacktrace());
1595
0
  }
1596
1597
0
  return true;
1598
0
}
1599
1600
bool cmGeneratorTarget::MacOSXRpathInstallNameDirDefault() const
1601
0
{
1602
  // we can't do rpaths when unsupported
1603
0
  if (!this->Makefile->IsSet("CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG")) {
1604
0
    return false;
1605
0
  }
1606
1607
0
  cmValue macosx_rpath_str = this->GetProperty("MACOSX_RPATH");
1608
0
  if (macosx_rpath_str) {
1609
0
    return this->GetPropertyAsBool("MACOSX_RPATH");
1610
0
  }
1611
1612
0
  return true;
1613
0
}
1614
1615
bool cmGeneratorTarget::MacOSXUseInstallNameDir() const
1616
0
{
1617
0
  cmValue build_with_install_name =
1618
0
    this->GetProperty("BUILD_WITH_INSTALL_NAME_DIR");
1619
0
  if (build_with_install_name) {
1620
0
    return build_with_install_name.IsOn();
1621
0
  }
1622
1623
0
  cmPolicies::PolicyStatus cmp0068 = this->GetPolicyStatusCMP0068();
1624
0
  if (cmp0068 == cmPolicies::NEW) {
1625
0
    return false;
1626
0
  }
1627
1628
0
  bool use_install_name = this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH");
1629
1630
0
  if (use_install_name && cmp0068 == cmPolicies::WARN) {
1631
0
    this->LocalGenerator->GetGlobalGenerator()->AddCMP0068WarnTarget(
1632
0
      this->GetName());
1633
0
  }
1634
1635
0
  return use_install_name;
1636
0
}
1637
1638
bool cmGeneratorTarget::CanGenerateInstallNameDir(
1639
  InstallNameType name_type) const
1640
0
{
1641
0
  cmPolicies::PolicyStatus cmp0068 = this->GetPolicyStatusCMP0068();
1642
1643
0
  if (cmp0068 == cmPolicies::NEW) {
1644
0
    return true;
1645
0
  }
1646
1647
0
  bool skip = this->Makefile->IsOn("CMAKE_SKIP_RPATH");
1648
0
  if (name_type == INSTALL_NAME_FOR_INSTALL) {
1649
0
    skip |= this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH");
1650
0
  } else {
1651
0
    skip |= this->GetPropertyAsBool("SKIP_BUILD_RPATH");
1652
0
  }
1653
1654
0
  if (skip && cmp0068 == cmPolicies::WARN) {
1655
0
    this->LocalGenerator->GetGlobalGenerator()->AddCMP0068WarnTarget(
1656
0
      this->GetName());
1657
0
  }
1658
1659
0
  return !skip;
1660
0
}
1661
1662
std::string cmGeneratorTarget::GetSOName(
1663
  std::string const& config, cmStateEnums::ArtifactType artifact) const
1664
0
{
1665
0
  if (this->IsImported()) {
1666
    // Lookup the imported soname.
1667
0
    if (cmGeneratorTarget::ImportInfo const* info =
1668
0
          this->GetImportInfo(config)) {
1669
0
      if (info->NoSOName) {
1670
        // The imported library has no builtin soname so the name
1671
        // searched at runtime will be just the filename.
1672
0
        return cmSystemTools::GetFilenameName(info->Location);
1673
0
      }
1674
      // Use the soname given if any.
1675
0
      if (this->IsFrameworkOnApple()) {
1676
0
        auto fwDescriptor = this->GetGlobalGenerator()->SplitFrameworkPath(
1677
0
          info->SOName, cmGlobalGenerator::FrameworkFormat::Strict);
1678
0
        if (fwDescriptor) {
1679
0
          return fwDescriptor->GetVersionedName();
1680
0
        }
1681
0
      }
1682
0
      if (cmHasLiteralPrefix(info->SOName, "@rpath/")) {
1683
0
        return info->SOName.substr(cmStrLen("@rpath/"));
1684
0
      }
1685
0
      return info->SOName;
1686
0
    }
1687
0
    return "";
1688
0
  }
1689
  // Compute the soname that will be built.
1690
0
  return artifact == cmStateEnums::RuntimeBinaryArtifact
1691
0
    ? this->GetLibraryNames(config).SharedObject
1692
0
    : this->GetLibraryNames(config).ImportLibrary;
1693
0
}
1694
1695
namespace {
1696
bool shouldAddFullLevel(cmGeneratorTarget::BundleDirectoryLevel level)
1697
0
{
1698
0
  return level == cmGeneratorTarget::FullLevel;
1699
0
}
1700
1701
bool shouldAddContentLevel(cmGeneratorTarget::BundleDirectoryLevel level)
1702
0
{
1703
0
  return level == cmGeneratorTarget::ContentLevel || shouldAddFullLevel(level);
1704
0
}
1705
}
1706
1707
std::string cmGeneratorTarget::GetAppBundleDirectory(
1708
  std::string const& config, BundleDirectoryLevel level) const
1709
0
{
1710
0
  std::string fpath = cmStrCat(
1711
0
    this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
1712
0
  cmValue ext = this->GetProperty("BUNDLE_EXTENSION");
1713
0
  fpath += (ext ? *ext : "app");
1714
0
  if (shouldAddContentLevel(level) &&
1715
0
      !this->Makefile->PlatformIsAppleEmbedded()) {
1716
0
    fpath += "/Contents";
1717
0
    if (shouldAddFullLevel(level)) {
1718
0
      fpath += "/MacOS";
1719
0
    }
1720
0
  }
1721
0
  return fpath;
1722
0
}
1723
1724
bool cmGeneratorTarget::IsBundleOnApple() const
1725
0
{
1726
0
  return this->IsFrameworkOnApple() || this->IsAppBundleOnApple() ||
1727
0
    this->IsCFBundleOnApple();
1728
0
}
1729
1730
bool cmGeneratorTarget::IsWin32Executable(std::string const& config) const
1731
0
{
1732
0
  return cmIsOn(cmGeneratorExpression::Evaluate(
1733
0
    this->GetSafeProperty("WIN32_EXECUTABLE"), this->LocalGenerator, config));
1734
0
}
1735
1736
std::string cmGeneratorTarget::GetCFBundleDirectory(
1737
  std::string const& config, BundleDirectoryLevel level) const
1738
0
{
1739
0
  std::string fpath = cmStrCat(
1740
0
    this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
1741
0
  std::string ext;
1742
0
  if (cmValue p = this->GetProperty("BUNDLE_EXTENSION")) {
1743
0
    ext = *p;
1744
0
  } else {
1745
0
    if (this->IsXCTestOnApple()) {
1746
0
      ext = "xctest";
1747
0
    } else {
1748
0
      ext = "bundle";
1749
0
    }
1750
0
  }
1751
0
  fpath += ext;
1752
0
  if (shouldAddContentLevel(level) &&
1753
0
      !this->Makefile->PlatformIsAppleEmbedded()) {
1754
0
    fpath += "/Contents";
1755
0
    if (shouldAddFullLevel(level)) {
1756
0
      fpath += "/MacOS";
1757
0
    }
1758
0
  }
1759
0
  return fpath;
1760
0
}
1761
1762
std::string cmGeneratorTarget::GetFrameworkDirectory(
1763
  std::string const& config, BundleDirectoryLevel level) const
1764
0
{
1765
0
  std::string fpath = cmStrCat(
1766
0
    this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
1767
0
  cmValue ext = this->GetProperty("BUNDLE_EXTENSION");
1768
0
  fpath += (ext ? *ext : "framework");
1769
0
  if (shouldAddFullLevel(level) &&
1770
0
      !this->Makefile->PlatformIsAppleEmbedded()) {
1771
0
    fpath =
1772
0
      cmStrCat(std::move(fpath), "/Versions/", this->GetFrameworkVersion());
1773
0
  }
1774
0
  return fpath;
1775
0
}
1776
1777
std::string cmGeneratorTarget::GetFullName(
1778
  std::string const& config, cmStateEnums::ArtifactType artifact) const
1779
0
{
1780
0
  if (this->IsImported()) {
1781
0
    return this->GetFullNameImported(config, artifact);
1782
0
  }
1783
0
  return this->GetFullNameInternal(config, artifact);
1784
0
}
1785
1786
std::string cmGeneratorTarget::GetInstallNameDirForBuildTree(
1787
  std::string const& config) const
1788
0
{
1789
0
  if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
1790
1791
    // If building directly for installation then the build tree install_name
1792
    // is the same as the install tree.
1793
0
    if (this->MacOSXUseInstallNameDir()) {
1794
0
      std::string installPrefix =
1795
0
        this->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
1796
0
      return this->GetInstallNameDirForInstallTree(config, installPrefix);
1797
0
    }
1798
1799
    // Use the build tree directory for the target.
1800
0
    if (this->CanGenerateInstallNameDir(INSTALL_NAME_FOR_BUILD)) {
1801
0
      std::string dir;
1802
0
      if (this->MacOSXRpathInstallNameDirDefault()) {
1803
0
        dir = "@rpath";
1804
0
      } else {
1805
0
        dir = this->GetDirectory(config);
1806
0
      }
1807
0
      dir += '/';
1808
0
      return dir;
1809
0
    }
1810
0
  }
1811
0
  return "";
1812
0
}
1813
1814
std::string cmGeneratorTarget::GetInstallNameDirForInstallTree(
1815
  std::string const& config, std::string const& installPrefix) const
1816
0
{
1817
0
  if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
1818
0
    std::string dir;
1819
0
    cmValue install_name_dir = this->GetProperty("INSTALL_NAME_DIR");
1820
1821
0
    if (this->CanGenerateInstallNameDir(INSTALL_NAME_FOR_INSTALL)) {
1822
0
      if (cmNonempty(install_name_dir)) {
1823
0
        dir = *install_name_dir;
1824
0
        cmGeneratorExpression::ReplaceInstallPrefix(dir, installPrefix);
1825
0
        dir =
1826
0
          cmGeneratorExpression::Evaluate(dir, this->LocalGenerator, config);
1827
0
        if (!dir.empty()) {
1828
0
          dir = cmStrCat(dir, '/');
1829
0
        }
1830
0
      }
1831
0
    }
1832
0
    if (!install_name_dir) {
1833
0
      if (this->MacOSXRpathInstallNameDirDefault()) {
1834
0
        dir = "@rpath/";
1835
0
      }
1836
0
    }
1837
0
    return dir;
1838
0
  }
1839
0
  return "";
1840
0
}
1841
1842
cmListFileBacktrace cmGeneratorTarget::GetBacktrace() const
1843
0
{
1844
0
  return this->Target->GetBacktrace();
1845
0
}
1846
1847
std::set<BT<std::pair<std::string, bool>>> const&
1848
cmGeneratorTarget::GetUtilities() const
1849
0
{
1850
0
  return this->Target->GetUtilities();
1851
0
}
1852
1853
bool cmGeneratorTarget::HaveWellDefinedOutputFiles() const
1854
0
{
1855
0
  return this->GetType() == cm::TargetType::STATIC_LIBRARY ||
1856
0
    this->GetType() == cm::TargetType::SHARED_LIBRARY ||
1857
0
    this->GetType() == cm::TargetType::MODULE_LIBRARY ||
1858
0
    this->GetType() == cm::TargetType::OBJECT_LIBRARY ||
1859
0
    this->GetType() == cm::TargetType::EXECUTABLE;
1860
0
}
1861
1862
std::string const* cmGeneratorTarget::GetExportMacro() const
1863
0
{
1864
  // Define the symbol for targets that export symbols.
1865
0
  if (this->GetType() == cm::TargetType::SHARED_LIBRARY ||
1866
0
      this->GetType() == cm::TargetType::MODULE_LIBRARY ||
1867
0
      this->IsExecutableWithExports()) {
1868
0
    if (cmValue custom_export_name = this->GetProperty("DEFINE_SYMBOL")) {
1869
0
      this->ExportMacro = *custom_export_name;
1870
0
    } else {
1871
0
      std::string in = cmStrCat(this->GetName(), "_EXPORTS");
1872
0
      this->ExportMacro = cmSystemTools::MakeCidentifier(in);
1873
0
    }
1874
0
    return &this->ExportMacro;
1875
0
  }
1876
0
  return nullptr;
1877
0
}
1878
1879
cmList const& cmGeneratorTarget::GetSharedLibraryCompileDefs(
1880
  std::string const& config) const
1881
0
{
1882
0
  {
1883
0
    auto it = this->SharedLibraryCompileDefs.find(config);
1884
0
    if (it != this->SharedLibraryCompileDefs.end()) {
1885
0
      return it->second;
1886
0
    }
1887
0
  }
1888
1889
0
  auto emplaceResult =
1890
0
    this->SharedLibraryCompileDefs.emplace(config, cmList{});
1891
0
  auto& defs = emplaceResult.first->second;
1892
0
  if (this->GetType() != cm::TargetType::SHARED_LIBRARY &&
1893
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY) {
1894
0
    return defs;
1895
0
  }
1896
1897
0
  if (this->GetPolicyStatusCMP0203() != cmPolicies::NEW) {
1898
0
    return defs;
1899
0
  }
1900
1901
0
  auto linkerLang = this->GetLinkerLanguage(config);
1902
0
  auto definitionVar =
1903
0
    cmStrCat("CMAKE_", linkerLang, "_SHARED_LIBRARY_COMPILE_DEFINITIONS");
1904
0
  defs = this->Makefile->GetSafeDefinition(definitionVar);
1905
1906
0
  return defs;
1907
0
}
1908
1909
cmGeneratorTarget::NameComponents const&
1910
cmGeneratorTarget::GetFullNameComponents(
1911
  std::string const& config, cmStateEnums::ArtifactType artifact) const
1912
0
{
1913
0
  return this->GetFullNameInternalComponents(config, artifact);
1914
0
}
1915
1916
std::string cmGeneratorTarget::BuildBundleDirectory(
1917
  std::string const& base, std::string const& config,
1918
  BundleDirectoryLevel level) const
1919
0
{
1920
0
  std::string fpath = base;
1921
0
  if (this->IsAppBundleOnApple()) {
1922
0
    fpath += this->GetAppBundleDirectory(config, level);
1923
0
  }
1924
0
  if (this->IsFrameworkOnApple()) {
1925
0
    fpath += this->GetFrameworkDirectory(config, level);
1926
0
  }
1927
0
  if (this->IsCFBundleOnApple()) {
1928
0
    fpath += this->GetCFBundleDirectory(config, level);
1929
0
  }
1930
0
  return fpath;
1931
0
}
1932
1933
std::string cmGeneratorTarget::GetMacContentDirectory(
1934
  std::string const& config, cmStateEnums::ArtifactType artifact) const
1935
0
{
1936
  // Start with the output directory for the target.
1937
0
  std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/');
1938
0
  BundleDirectoryLevel level = ContentLevel;
1939
0
  if (this->IsFrameworkOnApple()) {
1940
    // additional files with a framework go into the version specific
1941
    // directory
1942
0
    level = FullLevel;
1943
0
  }
1944
0
  fpath = this->BuildBundleDirectory(fpath, config, level);
1945
0
  return fpath;
1946
0
}
1947
1948
std::string cmGeneratorTarget::GetEffectiveFolderName() const
1949
0
{
1950
0
  std::string effectiveFolder;
1951
1952
0
  if (!this->GlobalGenerator->UseFolderProperty()) {
1953
0
    return effectiveFolder;
1954
0
  }
1955
1956
0
  cmValue targetFolder = this->GetProperty("FOLDER");
1957
0
  if (targetFolder) {
1958
0
    effectiveFolder += *targetFolder;
1959
0
  }
1960
1961
0
  return effectiveFolder;
1962
0
}
1963
1964
cmGeneratorTarget::CompileInfo const* cmGeneratorTarget::GetCompileInfo(
1965
  std::string const& config) const
1966
0
{
1967
  // There is no compile information for imported targets.
1968
0
  if (this->IsImported()) {
1969
0
    return nullptr;
1970
0
  }
1971
1972
0
  if (this->GetType() > cm::TargetType::OBJECT_LIBRARY) {
1973
0
    std::string msg = cmStrCat("cmTarget::GetCompileInfo called for ",
1974
0
                               this->GetName(), " which has type ",
1975
0
                               cmState::GetTargetTypeName(this->GetType()));
1976
0
    this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
1977
0
    return nullptr;
1978
0
  }
1979
1980
  // Lookup/compute/cache the compile information for this configuration.
1981
0
  std::string config_upper;
1982
0
  if (!config.empty()) {
1983
0
    config_upper = cmSystemTools::UpperCase(config);
1984
0
  }
1985
0
  auto i = this->CompileInfoMap.find(config_upper);
1986
0
  if (i == this->CompileInfoMap.end()) {
1987
0
    CompileInfo info;
1988
0
    this->ComputePDBOutputDir("COMPILE_PDB", config, info.CompilePdbDir);
1989
0
    CompileInfoMapType::value_type entry(config_upper, info);
1990
0
    i = this->CompileInfoMap.insert(entry).first;
1991
0
  }
1992
0
  return &i->second;
1993
0
}
1994
1995
cmGeneratorTarget::ModuleDefinitionInfo const*
1996
cmGeneratorTarget::GetModuleDefinitionInfo(std::string const& config) const
1997
0
{
1998
  // A module definition file only makes sense on certain target types.
1999
0
  if (this->GetType() != cm::TargetType::SHARED_LIBRARY &&
2000
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
2001
0
      !this->IsExecutableWithExports()) {
2002
0
    return nullptr;
2003
0
  }
2004
2005
  // Lookup/compute/cache the compile information for this configuration.
2006
0
  std::string config_upper;
2007
0
  if (!config.empty()) {
2008
0
    config_upper = cmSystemTools::UpperCase(config);
2009
0
  }
2010
0
  auto i = this->ModuleDefinitionInfoMap.find(config_upper);
2011
0
  if (i == this->ModuleDefinitionInfoMap.end()) {
2012
0
    ModuleDefinitionInfo info;
2013
0
    this->ComputeModuleDefinitionInfo(config, info);
2014
0
    ModuleDefinitionInfoMapType::value_type entry(config_upper, info);
2015
0
    i = this->ModuleDefinitionInfoMap.insert(entry).first;
2016
0
  }
2017
0
  return &i->second;
2018
0
}
2019
2020
void cmGeneratorTarget::ComputeModuleDefinitionInfo(
2021
  std::string const& config, ModuleDefinitionInfo& info) const
2022
0
{
2023
0
  this->GetModuleDefinitionSources(info.Sources, config);
2024
0
  info.WindowsExportAllSymbols =
2025
0
    this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
2026
0
    this->GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS");
2027
0
#if !defined(CMAKE_BOOTSTRAP)
2028
0
  info.DefFileGenerated =
2029
0
    info.WindowsExportAllSymbols || info.Sources.size() > 1;
2030
#else
2031
  // Our __create_def helper is not available during CMake bootstrap.
2032
  info.DefFileGenerated = false;
2033
#endif
2034
0
  if (info.DefFileGenerated) {
2035
0
    info.DefFile =
2036
0
      this->GetObjectDirectory(config) /* has slash */ + "exports.def";
2037
0
  } else if (!info.Sources.empty()) {
2038
0
    info.DefFile = info.Sources.front()->GetFullPath();
2039
0
  }
2040
0
}
2041
2042
bool cmGeneratorTarget::IsAIX() const
2043
0
{
2044
0
  return this->Target->IsAIX();
2045
0
}
2046
2047
bool cmGeneratorTarget::IsApple() const
2048
0
{
2049
0
  return this->Target->IsApple();
2050
0
}
2051
2052
bool cmGeneratorTarget::IsDLLPlatform() const
2053
0
{
2054
0
  return this->Target->IsDLLPlatform();
2055
0
}
2056
2057
void cmGeneratorTarget::GetAutoUicOptions(std::vector<std::string>& result,
2058
                                          std::string const& config) const
2059
0
{
2060
0
  char const* prop =
2061
0
    this->GetLinkInterfaceDependentStringProperty("AUTOUIC_OPTIONS", config);
2062
0
  if (!prop) {
2063
0
    return;
2064
0
  }
2065
2066
0
  cm::GenEx::Context context(this->LocalGenerator, config);
2067
0
  cmGeneratorExpressionDAGChecker dagChecker{
2068
0
    this, "AUTOUIC_OPTIONS", nullptr, nullptr, context,
2069
0
  };
2070
0
  cmExpandList(cmGeneratorExpression::Evaluate(
2071
0
                 prop, context.LG, context.Config, this, &dagChecker),
2072
0
               result);
2073
0
}
2074
2075
void cmGeneratorTarget::TraceDependencies()
2076
0
{
2077
  // CMake-generated targets have no dependencies to trace.  Normally tracing
2078
  // would find nothing anyway, but when building CMake itself the "install"
2079
  // target command ends up referencing the "cmake" target but we do not
2080
  // really want the dependency because "install" depend on "all" anyway.
2081
0
  if (this->GetType() == cm::TargetType::GLOBAL_TARGET) {
2082
0
    return;
2083
0
  }
2084
2085
  // Use a helper object to trace the dependencies.
2086
0
  cmTargetTraceDependencies tracer(this);
2087
0
  tracer.Trace();
2088
0
}
2089
2090
std::string cmGeneratorTarget::GetCompilePDBDirectory(
2091
  std::string const& config) const
2092
0
{
2093
0
  if (CompileInfo const* info = this->GetCompileInfo(config)) {
2094
0
    return info->CompilePdbDir;
2095
0
  }
2096
0
  return "";
2097
0
}
2098
2099
std::vector<std::string> cmGeneratorTarget::GetAppleArchs(
2100
  std::string const& config, cm::optional<std::string> lang) const
2101
0
{
2102
0
  cmList archList;
2103
0
  if (!this->IsApple()) {
2104
0
    return std::move(archList.data());
2105
0
  }
2106
0
  cmValue archs = nullptr;
2107
0
  if (!config.empty()) {
2108
0
    std::string defVarName =
2109
0
      cmStrCat("OSX_ARCHITECTURES_", cmSystemTools::UpperCase(config));
2110
0
    archs = this->GetProperty(defVarName);
2111
0
  }
2112
0
  if (!archs) {
2113
0
    archs = this->GetProperty("OSX_ARCHITECTURES");
2114
0
  }
2115
0
  if (archs) {
2116
0
    archList.assign(*archs);
2117
0
  }
2118
0
  if (archList.empty() &&
2119
      // Fall back to a default architecture if no compiler target is set.
2120
0
      (!lang ||
2121
0
       this->Makefile
2122
0
         ->GetDefinition(cmStrCat("CMAKE_", *lang, "_COMPILER_TARGET"))
2123
0
         .IsEmpty())) {
2124
0
    archList.assign(
2125
0
      this->Makefile->GetDefinition("_CMAKE_APPLE_ARCHS_DEFAULT"));
2126
0
  }
2127
0
  return std::move(archList.data());
2128
0
}
2129
2130
namespace {
2131
2132
bool IsSupportedClassifiedFlagsLanguage(std::string const& lang)
2133
0
{
2134
0
  return lang == "CXX"_s;
2135
0
}
2136
2137
bool CanUseCompilerLauncher(std::string const& lang)
2138
0
{
2139
  // Also found in `cmCommonTargetGenerator::GetCompilerLauncher`.
2140
0
  return lang == "C"_s || lang == "CXX"_s || lang == "Fortran"_s ||
2141
0
    lang == "CUDA"_s || lang == "HIP"_s || lang == "ISPC"_s ||
2142
0
    lang == "OBJC"_s || lang == "OBJCXX"_s;
2143
0
}
2144
2145
// FIXME: return a vector of `cm::string_view` instead to avoid lots of tiny
2146
// allocations.
2147
std::vector<std::string> SplitFlags(std::string const& flags)
2148
0
{
2149
0
  std::vector<std::string> options;
2150
2151
#ifdef _WIN32
2152
  cmSystemTools::ParseWindowsCommandLine(flags.c_str(), options);
2153
#else
2154
0
  cmSystemTools::ParseUnixCommandLine(flags.c_str(), options);
2155
0
#endif
2156
2157
0
  return options;
2158
0
}
2159
2160
}
2161
2162
cmGeneratorTarget::ClassifiedFlags
2163
cmGeneratorTarget::GetClassifiedFlagsForSource(cmSourceFile const* sf,
2164
                                               std::string const& config)
2165
0
{
2166
0
  auto& sourceFlagsCache = this->Configs[config].SourceFlags;
2167
0
  auto cacheEntry = sourceFlagsCache.lower_bound(sf);
2168
0
  if (cacheEntry != sourceFlagsCache.end() && cacheEntry->first == sf) {
2169
0
    return cacheEntry->second;
2170
0
  }
2171
2172
0
  ClassifiedFlags flags;
2173
0
  std::string const& lang = sf->GetLanguage();
2174
2175
0
  if (!IsSupportedClassifiedFlagsLanguage(lang)) {
2176
0
    return flags;
2177
0
  }
2178
2179
0
  auto* const lg = this->GetLocalGenerator();
2180
0
  auto const* const mf = this->Makefile;
2181
0
  cmGeneratorFileSet const* const fileSet =
2182
0
    this->GetFileSetForSource(config, sf);
2183
2184
  // Compute the compiler launcher flags.
2185
0
  if (CanUseCompilerLauncher(lang)) {
2186
    // Compiler launchers are all execution flags and should not be relevant to
2187
    // the actual compilation.
2188
0
    FlagClassification cls = FlagClassification::ExecutionFlag;
2189
0
    FlagKind kind = FlagKind::NotAFlag;
2190
2191
0
    std::string const clauncher_prop = cmStrCat(lang, "_COMPILER_LAUNCHER");
2192
0
    cmValue clauncher = this->GetProperty(clauncher_prop);
2193
0
    std::string const evaluatedClauncher = cmGeneratorExpression::Evaluate(
2194
0
      *clauncher, lg, config, this, nullptr, this, lang);
2195
2196
0
    for (auto const& flag : SplitFlags(evaluatedClauncher)) {
2197
0
      flags.emplace_back(cls, kind, flag);
2198
0
    }
2199
0
  }
2200
2201
0
  ClassifiedFlags define_flags;
2202
0
  ClassifiedFlags include_flags;
2203
0
  ClassifiedFlags compile_flags;
2204
2205
0
  SourceVariables sfVars = this->GetSourceVariables(sf, config);
2206
2207
  // Compute language flags.
2208
0
  {
2209
0
    FlagClassification cls = FlagClassification::BaselineFlag;
2210
0
    FlagKind kind = FlagKind::Compile;
2211
2212
0
    std::string mfFlags;
2213
    // Explicitly add the explicit language flag before any other flag
2214
    // so user flags can override it.
2215
0
    this->AddExplicitLanguageFlags(mfFlags, *sf);
2216
2217
0
    for (auto const& flag : SplitFlags(mfFlags)) {
2218
0
      flags.emplace_back(cls, kind, flag);
2219
0
    }
2220
0
  }
2221
2222
0
  std::unordered_map<std::string, std::string> pchSources;
2223
0
  std::string filterArch;
2224
2225
0
  {
2226
0
    std::vector<std::string> pchArchs = this->GetPchArchs(config, lang);
2227
2228
0
    for (std::string const& arch : pchArchs) {
2229
0
      std::string const pchSource = this->GetPchSource(config, lang, arch);
2230
0
      if (pchSource == sf->GetFullPath()) {
2231
0
        filterArch = arch;
2232
0
      }
2233
0
      if (!pchSource.empty()) {
2234
0
        pchSources.insert(std::make_pair(pchSource, arch));
2235
0
      }
2236
0
    }
2237
0
  }
2238
2239
  // File set specific flags
2240
0
  if (fileSet) {
2241
    // include flags
2242
0
    {
2243
0
      auto fsIncludes = fileSet->BelongsTo(this)
2244
0
        ? fileSet->GetIncludeDirectories(config, lang)
2245
0
        : fileSet->GetInterfaceIncludeDirectories(config, lang);
2246
0
      if (!fsIncludes.empty()) {
2247
0
        std::vector<std::string> includes;
2248
0
        lg->AppendIncludeDirectories(includes, cm::remove_BT(fsIncludes), *sf);
2249
2250
0
        auto includeFlags =
2251
0
          lg->GetIncludeFlags(includes, this, lang, config, false);
2252
2253
0
        for (auto&& flag : SplitFlags(includeFlags)) {
2254
0
          include_flags.emplace_back(FlagClassification::PrivateFlag,
2255
0
                                     FlagKind::Include, std::move(flag));
2256
0
        }
2257
0
      }
2258
0
    }
2259
0
  }
2260
2261
  // source specific flags
2262
0
  {
2263
    // include flags
2264
0
    if (cmValue srcIncludes = sf->GetProperty("INCLUDE_DIRECTORIES")) {
2265
0
      std::vector<std::string> includes;
2266
0
      lg->AppendIncludeDirectories(includes, srcIncludes, *sf);
2267
2268
0
      auto includeFlags =
2269
0
        lg->GetIncludeFlags(includes, this, lang, config, false);
2270
2271
0
      for (auto&& flag : SplitFlags(includeFlags)) {
2272
0
        include_flags.emplace_back(FlagClassification::PrivateFlag,
2273
0
                                   FlagKind::Include, std::move(flag));
2274
0
      }
2275
0
    }
2276
0
  }
2277
2278
  // Compute target-wide flags.
2279
0
  {
2280
0
    FlagClassification cls = FlagClassification::BaselineFlag;
2281
2282
    // Compile flags
2283
0
    {
2284
0
      FlagKind kind = FlagKind::Compile;
2285
0
      std::string targetFlags;
2286
2287
0
      lg->GetTargetCompileFlags(this, config, lang, targetFlags, filterArch);
2288
2289
0
      for (auto&& flag : SplitFlags(targetFlags)) {
2290
0
        compile_flags.emplace_back(cls, kind, std::move(flag));
2291
0
      }
2292
0
    }
2293
2294
    // Define flags
2295
0
    {
2296
0
      FlagKind kind = FlagKind::Definition;
2297
0
      std::set<std::string> defines;
2298
2299
0
      lg->GetTargetDefines(this, config, lang, defines);
2300
2301
0
      std::string defineFlags;
2302
0
      lg->JoinDefines(defines, defineFlags, lang);
2303
2304
0
      for (auto&& flag : SplitFlags(defineFlags)) {
2305
0
        define_flags.emplace_back(cls, kind, std::move(flag));
2306
0
      }
2307
0
    }
2308
2309
    // Include flags
2310
0
    {
2311
0
      FlagKind kind = FlagKind::Include;
2312
0
      std::vector<std::string> includes;
2313
2314
0
      lg->GetIncludeDirectories(includes, this, lang, config);
2315
0
      auto includeFlags =
2316
0
        lg->GetIncludeFlags(includes, this, lang, config, false);
2317
2318
0
      for (auto&& flag : SplitFlags(includeFlags)) {
2319
0
        include_flags.emplace_back(cls, kind, std::move(flag));
2320
0
      }
2321
0
    }
2322
0
  }
2323
2324
0
  std::string const COMPILE_OPTIONS("COMPILE_OPTIONS");
2325
0
  cmGeneratorExpressionInterpreter genexInterpreter(lg, config, this, lang);
2326
2327
  // Source-specific flags.
2328
0
  {
2329
    // Define flags
2330
0
    {
2331
0
      if (cmValue srcDefines = sf->GetProperty("COMPILE_DEFINITIONS")) {
2332
0
        std::set<std::string> defines;
2333
0
        lg->AppendDefines(defines, srcDefines);
2334
2335
0
        std::string defineFlags;
2336
0
        lg->JoinDefines(defines, defineFlags, lang);
2337
2338
0
        for (auto&& flag : SplitFlags(defineFlags)) {
2339
0
          define_flags.emplace_back(FlagClassification::PrivateFlag,
2340
0
                                    FlagKind::Definition, std::move(flag));
2341
0
        }
2342
0
      }
2343
0
    }
2344
2345
    // Compile flags.
2346
0
    {
2347
0
      std::string const COMPILE_FLAGS("COMPILE_FLAGS");
2348
2349
0
      FlagClassification cls = FlagClassification::PrivateFlag;
2350
0
      FlagKind kind = FlagKind::Compile;
2351
2352
0
      std::string sourceFlags;
2353
2354
0
      if (cmValue cflags = sf->GetProperty(COMPILE_FLAGS)) {
2355
0
        lg->AppendFlags(sourceFlags,
2356
0
                        genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
2357
0
      }
2358
2359
0
      if (cmValue coptions = sf->GetProperty(COMPILE_OPTIONS)) {
2360
0
        lg->AppendCompileOptions(
2361
0
          sourceFlags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
2362
0
      }
2363
2364
0
      for (auto&& flag : SplitFlags(sourceFlags)) {
2365
0
        compile_flags.emplace_back(cls, kind, std::move(flag));
2366
0
      }
2367
0
    }
2368
0
  }
2369
2370
  // File set specific flags
2371
0
  if (fileSet) {
2372
    // Define flags
2373
0
    {
2374
0
      auto fsDefines = fileSet->BelongsTo(this)
2375
0
        ? fileSet->GetCompileDefinitions(config, lang)
2376
0
        : fileSet->GetInterfaceCompileDefinitions(config, lang);
2377
0
      if (!fsDefines.empty()) {
2378
0
        std::set<std::string> defines;
2379
0
        lg->AppendDefines(defines, fsDefines);
2380
2381
0
        std::string defineFlags;
2382
0
        lg->JoinDefines(defines, defineFlags, lang);
2383
2384
0
        for (auto&& flag : SplitFlags(defineFlags)) {
2385
0
          define_flags.emplace_back(FlagClassification::PrivateFlag,
2386
0
                                    FlagKind::Definition, std::move(flag));
2387
0
        }
2388
0
      }
2389
0
    }
2390
2391
    // Compile flags.
2392
0
    {
2393
0
      auto options = fileSet->BelongsTo(this)
2394
0
        ? fileSet->GetCompileOptions(config, lang)
2395
0
        : fileSet->GetInterfaceCompileOptions(config, lang);
2396
0
      if (!options.empty()) {
2397
0
        std::string compileFlags;
2398
0
        lg->AppendCompileOptions(compileFlags, cm::remove_BT(options));
2399
2400
0
        for (auto&& flag : SplitFlags(compileFlags)) {
2401
0
          compile_flags.emplace_back(FlagClassification::PrivateFlag,
2402
0
                                     FlagKind::Compile, std::move(flag));
2403
0
        }
2404
0
      }
2405
0
    }
2406
0
  }
2407
2408
  // Dependency tracking flags.
2409
0
  {
2410
0
    if (!sfVars.DependencyFlags.empty()) {
2411
0
      cmRulePlaceholderExpander::RuleVariables vars;
2412
0
      auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
2413
2414
0
      vars.DependencyFile = sfVars.DependencyFile.c_str();
2415
0
      vars.DependencyTarget = sfVars.DependencyTarget.c_str();
2416
2417
0
      std::string depfileFlags = sfVars.DependencyFlags;
2418
0
      rulePlaceholderExpander->ExpandRuleVariables(lg, depfileFlags, vars);
2419
0
      for (auto&& flag : SplitFlags(depfileFlags)) {
2420
0
        compile_flags.emplace_back(FlagClassification::LocationFlag,
2421
0
                                   FlagKind::BuildSystem, std::move(flag));
2422
0
      }
2423
0
    }
2424
0
  }
2425
2426
  // Precompiled headers.
2427
0
  {
2428
0
    FlagClassification cls = FlagClassification::PrivateFlag;
2429
0
    FlagKind kind = FlagKind::Compile;
2430
2431
0
    std::string pchFlags;
2432
2433
    // Add precompile headers compile options.
2434
0
    if (!((fileSet && sf->GetProperty("SKIP_PRECOMPILE_HEADERS")) ||
2435
0
          sf->GetProperty("SKIP_PRECOMPILE_HEADERS"))) {
2436
0
      if (!pchSources.empty()) {
2437
0
        std::string pchOptions;
2438
0
        auto pchIt = pchSources.find(sf->GetFullPath());
2439
0
        if (pchIt != pchSources.end()) {
2440
0
          pchOptions =
2441
0
            this->GetPchCreateCompileOptions(config, lang, pchIt->second);
2442
0
        } else {
2443
0
          pchOptions = this->GetPchUseCompileOptions(config, lang);
2444
0
        }
2445
2446
0
        this->LocalGenerator->AppendCompileOptions(
2447
0
          pchFlags, genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
2448
0
      }
2449
0
    }
2450
2451
0
    for (auto&& flag : SplitFlags(pchFlags)) {
2452
0
      compile_flags.emplace_back(cls, kind, std::move(flag));
2453
0
    }
2454
0
  }
2455
2456
  // C++ module flags.
2457
0
  bool useBmiTemplate = false;
2458
0
  if (lang == "CXX"_s) {
2459
0
    FlagClassification cls = FlagClassification::LocationFlag;
2460
0
    FlagKind kind = FlagKind::BuildSystem;
2461
2462
0
    std::string bmiFlags;
2463
2464
0
    auto const* fs = this->GetFileSetForSource(config, sf);
2465
0
    if (fs && fs->GetType() == cm::FileSetMetadata::CXX_MODULES) {
2466
0
      if (lang != "CXX"_s) {
2467
0
        mf->IssueMessage(
2468
0
          MessageType::FATAL_ERROR,
2469
0
          cmStrCat(
2470
0
            "Target \"", this->Target->GetName(), "\" contains the source\n  ",
2471
0
            sf->GetFullPath(), "\nin a file set of type \"", fs->GetType(),
2472
0
            R"(" but the source is not classified as a "CXX" source.)"));
2473
0
      }
2474
2475
0
      if (!this->Target->IsNormal()) {
2476
0
        if (!mf->GetDefinition("CMAKE_CXX_COMPILE_BMI").IsEmpty()) {
2477
0
          useBmiTemplate = true;
2478
0
        } else {
2479
0
          std::string flag =
2480
0
            mf->GetSafeDefinition("CMAKE_CXX_MODULE_BMI_ONLY_FLAG");
2481
0
          cmRulePlaceholderExpander::RuleVariables compileObjectVars;
2482
0
          compileObjectVars.Object = sfVars.ObjectFileDir.c_str();
2483
0
          auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
2484
0
          rulePlaceholderExpander->ExpandRuleVariables(lg, flag,
2485
0
                                                       compileObjectVars);
2486
0
          lg->AppendCompileOptions(bmiFlags, flag);
2487
0
        }
2488
0
      }
2489
0
    }
2490
2491
0
    for (auto&& flag : SplitFlags(bmiFlags)) {
2492
0
      compile_flags.emplace_back(cls, kind, std::move(flag));
2493
0
    }
2494
0
  }
2495
2496
0
  cmRulePlaceholderExpander::RuleVariables vars;
2497
0
  vars.CMTargetName = this->GetName().c_str();
2498
0
  vars.CMTargetType = cmState::GetTargetTypeName(this->GetType()).c_str();
2499
0
  vars.Language = lang.c_str();
2500
2501
0
  auto const sfPath = this->LocalGenerator->ConvertToOutputFormat(
2502
0
    sf->GetFullPath(), cmOutputConverter::SHELL);
2503
2504
  // Compute the base compiler command line. We'll find placeholders and
2505
  // replace them with arguments later in this function.
2506
0
  {
2507
0
    FlagClassification cls = FlagClassification::ExecutionFlag;
2508
0
    FlagKind kind = FlagKind::NotAFlag;
2509
2510
0
    std::string const cmdVar =
2511
0
      cmStrCat("CMAKE_", lang, "_COMPILE_", useBmiTemplate ? "BMI" : "OBJECT");
2512
0
    std::string const& compileCmd = mf->GetRequiredDefinition(cmdVar);
2513
0
    cmList compileCmds(compileCmd); // FIXME: which command to use?
2514
0
    std::string& cmd = compileCmds[0];
2515
0
    auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
2516
2517
0
    static std::string const PlaceholderDefines = "__CMAKE_DEFINES";
2518
0
    static std::string const PlaceholderIncludes = "__CMAKE_INCLUDES";
2519
0
    static std::string const PlaceholderFlags = "__CMAKE_FLAGS";
2520
0
    static std::string const PlaceholderSource = "__CMAKE_SOURCE";
2521
2522
0
    vars.Defines = PlaceholderDefines.c_str();
2523
0
    vars.Includes = PlaceholderIncludes.c_str();
2524
0
    vars.TargetPDB = sfVars.TargetPDB.c_str();
2525
0
    vars.TargetCompilePDB = sfVars.TargetCompilePDB.c_str();
2526
0
    vars.Object = sfVars.ObjectFileDir.c_str();
2527
0
    vars.ObjectDir = sfVars.ObjectDir.c_str();
2528
0
    vars.ObjectFileDir = sfVars.ObjectFileDir.c_str();
2529
0
    vars.TargetSupportDir = sfVars.TargetSupportDir.c_str();
2530
0
    vars.Flags = PlaceholderFlags.c_str();
2531
0
    vars.DependencyFile = sfVars.DependencyFile.c_str();
2532
0
    vars.DependencyTarget = sfVars.DependencyTarget.c_str();
2533
0
    vars.Source = PlaceholderSource.c_str();
2534
2535
0
    rulePlaceholderExpander->ExpandRuleVariables(lg, cmd, vars);
2536
0
    for (auto&& flag : SplitFlags(cmd)) {
2537
0
      if (flag == PlaceholderDefines) {
2538
0
        flags.insert(flags.end(), define_flags.begin(), define_flags.end());
2539
0
      } else if (flag == PlaceholderIncludes) {
2540
0
        flags.insert(flags.end(), include_flags.begin(), include_flags.end());
2541
0
      } else if (flag == PlaceholderFlags) {
2542
0
        flags.insert(flags.end(), compile_flags.begin(), compile_flags.end());
2543
0
      } else if (flag == PlaceholderSource) {
2544
0
        flags.emplace_back(FlagClassification::LocationFlag,
2545
0
                           FlagKind::BuildSystem, sfPath);
2546
0
      } else {
2547
0
        flags.emplace_back(cls, kind, std::move(flag));
2548
        // All remaining flags here are build system flags.
2549
0
        kind = FlagKind::BuildSystem;
2550
0
      }
2551
0
    }
2552
0
  }
2553
2554
0
  cacheEntry = sourceFlagsCache.emplace_hint(cacheEntry, sf, std::move(flags));
2555
0
  return cacheEntry->second;
2556
0
}
2557
2558
cmGeneratorTarget::SourceVariables cmGeneratorTarget::GetSourceVariables(
2559
  cmSourceFile const* sf, std::string const& config)
2560
0
{
2561
0
  SourceVariables vars;
2562
0
  auto const language = sf->GetLanguage();
2563
0
  auto const targetType = this->GetType();
2564
0
  auto const* const lg = this->GetLocalGenerator();
2565
0
  auto const* const gg = this->GetGlobalGenerator();
2566
0
  auto const* const mf = this->Makefile;
2567
2568
  // PDB settings.
2569
0
  {
2570
0
    if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
2571
0
        mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
2572
0
        mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
2573
0
      std::string pdbPath;
2574
0
      std::string compilePdbPath;
2575
0
      if (targetType <= cm::TargetType::OBJECT_LIBRARY) {
2576
0
        compilePdbPath = this->GetCompilePDBPath(config);
2577
0
        if (compilePdbPath.empty()) {
2578
          // Match VS default: `$(IntDir)vc$(PlatformToolsetVersion).pdb`.
2579
          // A trailing slash tells the toolchain to add its default file name.
2580
0
          compilePdbPath = this->GetSupportDirectory();
2581
0
          if (gg->IsMultiConfig()) {
2582
0
            compilePdbPath = cmStrCat(compilePdbPath, '/', config);
2583
0
          }
2584
0
          compilePdbPath += '/';
2585
0
          if (targetType == cm::TargetType::STATIC_LIBRARY) {
2586
            // Match VS default for static libs: `$(IntDir)$(ProjectName).pdb`.
2587
0
            compilePdbPath = cmStrCat(compilePdbPath, this->GetName(), ".pdb");
2588
0
          }
2589
0
        }
2590
0
      }
2591
2592
0
      if (targetType == cm::TargetType::EXECUTABLE ||
2593
0
          targetType == cm::TargetType::STATIC_LIBRARY ||
2594
0
          targetType == cm::TargetType::SHARED_LIBRARY ||
2595
0
          targetType == cm::TargetType::MODULE_LIBRARY) {
2596
0
        pdbPath = cmStrCat(this->GetPDBDirectory(config), '/',
2597
0
                           this->GetPDBName(config));
2598
0
      }
2599
2600
0
      vars.TargetPDB = lg->ConvertToOutputFormat(
2601
0
        gg->ConvertToOutputPath(std::move(pdbPath)), cmOutputConverter::SHELL);
2602
0
      vars.TargetCompilePDB = lg->ConvertToOutputFormat(
2603
0
        gg->ConvertToOutputPath(std::move(compilePdbPath)),
2604
0
        cmOutputConverter::SHELL);
2605
0
    }
2606
0
  }
2607
2608
  // Object settings.
2609
0
  {
2610
0
    std::string const targetSupportDir = lg->MaybeRelativeToTopBinDir(
2611
0
      gg->ConvertToOutputPath(this->GetCMFSupportDirectory()));
2612
0
    std::string const objectDir = gg->ConvertToOutputPath(
2613
0
      cmStrCat(this->GetSupportDirectory(), gg->GetConfigDirectory(config)));
2614
0
    std::string const objectFileName = this->GetObjectName(sf);
2615
0
    std::string const objectFilePath =
2616
0
      cmStrCat(objectDir, '/', objectFileName);
2617
2618
0
    vars.TargetSupportDir =
2619
0
      lg->ConvertToOutputFormat(targetSupportDir, cmOutputConverter::SHELL);
2620
0
    vars.ObjectDir =
2621
0
      lg->ConvertToOutputFormat(objectDir, cmOutputConverter::SHELL);
2622
0
    vars.ObjectFileDir =
2623
0
      lg->ConvertToOutputFormat(objectFilePath, cmOutputConverter::SHELL);
2624
2625
    // Dependency settings.
2626
0
    {
2627
0
      std::string const depfileFormatName =
2628
0
        cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT");
2629
0
      std::string const depfileFormat =
2630
0
        mf->GetSafeDefinition(depfileFormatName);
2631
0
      if (depfileFormat != "msvc"_s) {
2632
0
        std::string const flagsName =
2633
0
          cmStrCat("CMAKE_DEPFILE_FLAGS_", language);
2634
0
        std::string const depfileFlags = mf->GetSafeDefinition(flagsName);
2635
0
        if (!depfileFlags.empty()) {
2636
0
          bool replaceExt = false;
2637
0
          if (!language.empty()) {
2638
0
            std::string const repVar =
2639
0
              cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
2640
0
            replaceExt = mf->IsOn(repVar);
2641
0
          }
2642
0
          std::string const depfilePath = cmStrCat(
2643
0
            objectDir, '/',
2644
0
            replaceExt
2645
0
              ? cmSystemTools::GetFilenameWithoutLastExtension(objectFileName)
2646
0
              : objectFileName,
2647
0
            ".d");
2648
2649
0
          vars.DependencyFlags = depfileFlags;
2650
0
          vars.DependencyTarget = vars.ObjectFileDir;
2651
0
          vars.DependencyFile =
2652
0
            lg->ConvertToOutputFormat(depfilePath, cmOutputConverter::SHELL);
2653
0
        }
2654
0
      }
2655
0
    }
2656
0
  }
2657
2658
0
  return vars;
2659
0
}
2660
2661
void cmGeneratorTarget::AddExplicitLanguageFlags(std::string& flags,
2662
                                                 cmSourceFile const& sf) const
2663
0
{
2664
0
  cmValue lang = sf.GetProperty("LANGUAGE");
2665
0
  if (!lang) {
2666
0
    return;
2667
0
  }
2668
2669
0
  switch (this->GetPolicyStatusCMP0119()) {
2670
0
    case cmPolicies::WARN:
2671
0
      CM_FALLTHROUGH;
2672
0
    case cmPolicies::OLD:
2673
      // The OLD behavior is to not add explicit language flags.
2674
0
      return;
2675
0
    case cmPolicies::NEW:
2676
      // The NEW behavior is to add explicit language flags.
2677
0
      break;
2678
0
  }
2679
2680
0
  this->LocalGenerator->AppendFeatureOptions(flags, *lang,
2681
0
                                             "EXPLICIT_LANGUAGE");
2682
0
}
2683
2684
void cmGeneratorTarget::AddCUDAArchitectureFlags(cmBuildStep compileOrLink,
2685
                                                 std::string const& config,
2686
                                                 std::string& flags) const
2687
0
{
2688
0
  std::string arch = this->GetSafeProperty("CUDA_ARCHITECTURES");
2689
2690
0
  if (arch.empty()) {
2691
0
    switch (this->GetPolicyStatusCMP0104()) {
2692
0
      case cmPolicies::WARN:
2693
0
        if (!this->LocalGenerator->GetCMakeInstance()->GetIsInTryCompile()) {
2694
0
          this->Makefile->IssuePolicyWarning(
2695
0
            cmPolicies::CMP0104, {},
2696
0
            cmStrCat("CUDA_ARCHITECTURES is empty for target \""_s,
2697
0
                     this->GetName(), "\"."_s));
2698
0
        }
2699
0
        CM_FALLTHROUGH;
2700
0
      case cmPolicies::OLD:
2701
0
        break;
2702
0
      default:
2703
0
        this->Makefile->IssueMessage(
2704
0
          MessageType::FATAL_ERROR,
2705
0
          cmStrCat("CUDA_ARCHITECTURES is empty for target \"",
2706
0
                   this->GetName(), "\"."));
2707
0
    }
2708
0
  }
2709
2710
  // If CUDA_ARCHITECTURES is false we don't add any architectures.
2711
0
  if (cmIsOff(arch)) {
2712
0
    return;
2713
0
  }
2714
2715
0
  this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "CUDA",
2716
0
                                     std::move(arch), flags);
2717
0
}
2718
2719
void cmGeneratorTarget::AddCUDAArchitectureFlagsImpl(cmBuildStep compileOrLink,
2720
                                                     std::string const& config,
2721
                                                     std::string const& lang,
2722
                                                     std::string arch,
2723
                                                     std::string& flags) const
2724
0
{
2725
0
  std::string const& compiler = this->Makefile->GetSafeDefinition(
2726
0
    cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
2727
0
  bool const ipoEnabled = this->IsIPOEnabled(lang, config);
2728
2729
  // Check for special modes: `all`, `all-major`.
2730
0
  if (arch == "all" || arch == "all-major") {
2731
0
    if (compiler == "NVIDIA" &&
2732
0
        cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
2733
0
                                      this->Makefile->GetDefinition(cmStrCat(
2734
0
                                        "CMAKE_", lang, "_COMPILER_VERSION")),
2735
0
                                      "11.5")) {
2736
0
      flags = cmStrCat(flags, " -arch=", arch);
2737
0
      return;
2738
0
    }
2739
0
    if (arch == "all") {
2740
0
      arch = *this->Makefile->GetDefinition(
2741
0
        cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL"));
2742
0
    } else if (arch == "all-major") {
2743
0
      arch = *this->Makefile->GetDefinition(
2744
0
        cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL_MAJOR"));
2745
0
    }
2746
0
  } else if (arch == "native") {
2747
0
    cmValue native = this->Makefile->GetDefinition(
2748
0
      cmStrCat("CMAKE_", lang, "_ARCHITECTURES_NATIVE"));
2749
0
    if (native.IsEmpty()) {
2750
0
      this->Makefile->IssueMessage(
2751
0
        MessageType::FATAL_ERROR,
2752
0
        cmStrCat(lang,
2753
0
                 "_ARCHITECTURES is set to \"native\", but no NVIDIA GPU was "
2754
0
                 "detected."));
2755
0
    }
2756
0
    if (compiler == "NVIDIA" &&
2757
0
        cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
2758
0
                                      this->Makefile->GetDefinition(cmStrCat(
2759
0
                                        "CMAKE_", lang, "_COMPILER_VERSION")),
2760
0
                                      "11.6")) {
2761
0
      flags = cmStrCat(flags, " -arch=", arch);
2762
0
      return;
2763
0
    }
2764
0
    arch = *native;
2765
0
  }
2766
2767
0
  struct CudaArchitecture
2768
0
  {
2769
0
    std::string name;
2770
0
    bool real{ true };
2771
0
    bool virtual_{ true };
2772
0
  };
2773
0
  std::vector<CudaArchitecture> architectures;
2774
2775
0
  {
2776
0
    cmList options(arch);
2777
2778
0
    for (auto& option : options) {
2779
0
      CudaArchitecture architecture;
2780
2781
      // Architecture name is up to the first specifier.
2782
0
      std::size_t pos = option.find_first_of('-');
2783
0
      architecture.name = option.substr(0, pos);
2784
2785
0
      if (pos != std::string::npos) {
2786
0
        cm::string_view specifier{ option.c_str() + pos + 1,
2787
0
                                   option.length() - pos - 1 };
2788
2789
0
        if (specifier == "real") {
2790
0
          architecture.real = true;
2791
0
          architecture.virtual_ = false;
2792
0
        } else if (specifier == "virtual") {
2793
0
          architecture.real = false;
2794
0
          architecture.virtual_ = true;
2795
0
        } else {
2796
0
          this->Makefile->IssueMessage(
2797
0
            MessageType::FATAL_ERROR,
2798
0
            cmStrCat("Unknown CUDA architecture specifier \"", specifier,
2799
0
                     "\"."));
2800
0
        }
2801
0
      }
2802
2803
0
      architectures.emplace_back(architecture);
2804
0
    }
2805
0
  }
2806
2807
0
  if (compiler == "NVIDIA") {
2808
0
    if (ipoEnabled && compileOrLink == cmBuildStep::Link) {
2809
0
      if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
2810
0
            cmStrCat("CMAKE_", lang, "_LINK_OPTIONS_IPO"))) {
2811
0
        flags += *cudaIPOFlags;
2812
0
      }
2813
0
    }
2814
2815
0
    for (CudaArchitecture& architecture : architectures) {
2816
0
      flags = cmStrCat(std::move(flags), " \"--generate-code=arch=compute_",
2817
0
                       architecture.name, ",code=[");
2818
2819
0
      if (architecture.virtual_) {
2820
0
        flags = cmStrCat(std::move(flags), "compute_", architecture.name);
2821
2822
0
        if (ipoEnabled || architecture.real) {
2823
0
          flags += ',';
2824
0
        }
2825
0
      }
2826
2827
0
      if (ipoEnabled) {
2828
0
        if (compileOrLink == cmBuildStep::Compile) {
2829
0
          flags = cmStrCat(std::move(flags), "lto_", architecture.name);
2830
0
        } else if (compileOrLink == cmBuildStep::Link) {
2831
0
          flags = cmStrCat(std::move(flags), "sm_", architecture.name);
2832
0
        }
2833
0
      } else if (architecture.real) {
2834
0
        flags = cmStrCat(std::move(flags), "sm_", architecture.name);
2835
0
      }
2836
2837
0
      flags += "]\"";
2838
0
    }
2839
0
  } else if (compiler == "Clang" && compileOrLink == cmBuildStep::Compile) {
2840
0
    for (CudaArchitecture& architecture : architectures) {
2841
0
      flags =
2842
0
        cmStrCat(std::move(flags), " --cuda-gpu-arch=sm_", architecture.name);
2843
2844
0
      if (!architecture.real) {
2845
0
        this->Makefile->IssueMessage(
2846
0
          MessageType::WARNING,
2847
0
          "Clang doesn't support disabling CUDA real code generation.");
2848
0
      }
2849
2850
0
      if (!architecture.virtual_) {
2851
0
        flags = cmStrCat(std::move(flags), " --no-cuda-include-ptx=sm_",
2852
0
                         architecture.name);
2853
0
      }
2854
0
    }
2855
0
  }
2856
0
}
2857
2858
void cmGeneratorTarget::AddISPCTargetFlags(std::string& flags) const
2859
0
{
2860
0
  std::string const& arch = this->GetSafeProperty("ISPC_INSTRUCTION_SETS");
2861
2862
  // If ISPC_TARGET is false we don't add any architectures.
2863
0
  if (cmIsOff(arch)) {
2864
0
    return;
2865
0
  }
2866
2867
0
  std::string const& compiler =
2868
0
    this->Makefile->GetSafeDefinition("CMAKE_ISPC_COMPILER_ID");
2869
2870
0
  if (compiler == "Intel") {
2871
0
    cmList targets(arch);
2872
0
    if (!targets.empty()) {
2873
0
      flags += cmStrCat(" --target=", cmWrap("", targets, "", ","));
2874
0
    }
2875
0
  }
2876
0
}
2877
2878
void cmGeneratorTarget::AddHIPArchitectureFlags(cmBuildStep compileOrLink,
2879
                                                std::string const& config,
2880
                                                std::string& flags) const
2881
0
{
2882
0
  std::string arch = this->GetSafeProperty("HIP_ARCHITECTURES");
2883
2884
0
  if (arch.empty()) {
2885
0
    this->Makefile->IssueMessage(
2886
0
      MessageType::FATAL_ERROR,
2887
0
      cmStrCat("HIP_ARCHITECTURES is empty for target \"", this->GetName(),
2888
0
               "\"."));
2889
0
  }
2890
2891
  // If HIP_ARCHITECTURES is false we don't add any architectures.
2892
0
  if (cmIsOff(arch)) {
2893
0
    return;
2894
0
  }
2895
2896
0
  if (this->Makefile->GetSafeDefinition("CMAKE_HIP_PLATFORM") == "nvidia") {
2897
0
    this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "HIP",
2898
0
                                       std::move(arch), flags);
2899
0
    return;
2900
0
  }
2901
2902
  // For spirv platform, chipStar handles targeting via the hip package
2903
0
  if (this->Makefile->GetSafeDefinition("CMAKE_HIP_PLATFORM") == "spirv") {
2904
0
    return;
2905
0
  }
2906
2907
0
  cmList options(arch);
2908
2909
0
  for (std::string& option : options) {
2910
0
    flags = cmStrCat(std::move(flags), " --offload-arch=", option);
2911
0
  }
2912
0
}
2913
2914
void cmGeneratorTarget::AddRustTargetFlags(std::string& flags) const
2915
0
{
2916
0
  cmValue const edition = this->GetProperty("Rust_EDITION");
2917
0
  if (edition && !edition->empty()) {
2918
0
    flags = cmStrCat(std::move(flags), " --edition=", *edition);
2919
0
  }
2920
0
}
2921
2922
void cmGeneratorTarget::AddSwiftTargetFlags(std::string& flags) const
2923
0
{
2924
0
  if (cmValue version = GetProperty("Swift_LANGUAGE_VERSION")) {
2925
0
    if (cmSystemTools::VersionCompare(
2926
0
          cmSystemTools::OP_GREATER_EQUAL,
2927
0
          this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
2928
0
          "4.2")) {
2929
0
      flags = cmStrCat(std::move(flags), " -swift-version ", *version);
2930
0
    }
2931
0
  }
2932
2933
0
  if (!this->GetGlobalGenerator()->IsXcode() &&
2934
0
      cmSystemTools::VersionCompare(
2935
0
        cmSystemTools::OP_GREATER_EQUAL,
2936
0
        this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
2937
0
        "5.8")) {
2938
    // Note: The Xcode generator sets the `SWIFT_PACKAGE_NAME` BuildSettings
2939
    //       attribute
2940
0
    std::string const packageName = this->GetSwiftPackageName();
2941
0
    if (!packageName.empty()) {
2942
0
      std::string const packageFlag =
2943
0
        this->Makefile->GetSafeDefinition("CMAKE_Swift_PACKAGE_NAME_FLAG");
2944
      // Add the package name to the flags
2945
0
      flags = cmStrCat(std::move(flags), ' ', packageFlag, ' ', packageName);
2946
0
    }
2947
0
  }
2948
0
}
2949
2950
void cmGeneratorTarget::AddCUDAToolkitFlags(std::string& flags) const
2951
0
{
2952
0
  std::string const& compiler =
2953
0
    this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID");
2954
2955
0
  if (compiler == "Clang") {
2956
    // Pass CUDA toolkit explicitly to Clang.
2957
    // Clang's searching for the system CUDA toolkit isn't very good and it's
2958
    // expected the user will explicitly pass the toolkit path.
2959
    // This also avoids Clang having to search for the toolkit on every
2960
    // invocation.
2961
0
    std::string toolkitRoot =
2962
0
      this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_LIBRARY_ROOT");
2963
2964
0
    if (!toolkitRoot.empty()) {
2965
0
      flags = cmStrCat(std::move(flags), " --cuda-path=",
2966
0
                       this->LocalGenerator->ConvertToOutputFormat(
2967
0
                         toolkitRoot, cmOutputConverter::SHELL));
2968
0
    }
2969
0
  }
2970
0
}
2971
2972
//----------------------------------------------------------------------------
2973
std::string cmGeneratorTarget::GetFeatureSpecificLinkRuleVariable(
2974
  std::string const& var, std::string const& lang,
2975
  std::string const& config) const
2976
0
{
2977
0
  if (this->IsIPOEnabled(lang, config)) {
2978
0
    std::string varIPO = var + "_IPO";
2979
0
    if (this->Makefile->IsDefinitionSet(varIPO)) {
2980
0
      return varIPO;
2981
0
    }
2982
0
  }
2983
2984
0
  return var;
2985
0
}
2986
2987
//----------------------------------------------------------------------------
2988
std::string cmGeneratorTarget::GetCreateRuleVariable(
2989
  std::string const& lang, std::string const& config) const
2990
0
{
2991
0
  switch (this->GetType()) {
2992
0
    case cm::TargetType::STATIC_LIBRARY: {
2993
0
      std::string var = cmStrCat("CMAKE_", lang, "_CREATE_STATIC_LIBRARY");
2994
0
      return this->GetFeatureSpecificLinkRuleVariable(var, lang, config);
2995
0
    }
2996
0
    case cm::TargetType::SHARED_LIBRARY:
2997
0
      if (this->IsArchivedAIXSharedLibrary()) {
2998
0
        return cmStrCat("CMAKE_", lang, "_CREATE_SHARED_LIBRARY_ARCHIVE");
2999
0
      }
3000
0
      return cmStrCat("CMAKE_", lang, "_CREATE_SHARED_LIBRARY");
3001
0
    case cm::TargetType::MODULE_LIBRARY:
3002
0
      return cmStrCat("CMAKE_", lang, "_CREATE_SHARED_MODULE");
3003
0
    case cm::TargetType::EXECUTABLE:
3004
0
      if (this->IsExecutableWithExports()) {
3005
0
        std::string linkExeWithExports =
3006
0
          cmStrCat("CMAKE_", lang, "_LINK_EXECUTABLE_WITH_EXPORTS");
3007
0
        if (this->Makefile->IsDefinitionSet(linkExeWithExports)) {
3008
0
          return linkExeWithExports;
3009
0
        }
3010
0
      }
3011
0
      return cmStrCat("CMAKE_", lang, "_LINK_EXECUTABLE");
3012
0
    default:
3013
0
      break;
3014
0
  }
3015
0
  return {};
3016
0
}
3017
3018
//----------------------------------------------------------------------------
3019
std::string cmGeneratorTarget::GetClangTidyExportFixesDirectory(
3020
  std::string const& lang) const
3021
0
{
3022
0
  cmValue val =
3023
0
    this->GetProperty(cmStrCat(lang, "_CLANG_TIDY_EXPORT_FIXES_DIR"));
3024
0
  if (!cmNonempty(val)) {
3025
0
    return {};
3026
0
  }
3027
3028
0
  std::string path = *val;
3029
0
  if (!cmSystemTools::FileIsFullPath(path)) {
3030
0
    path =
3031
0
      cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', path);
3032
0
  }
3033
0
  return cmSystemTools::CollapseFullPath(path);
3034
0
}
3035
3036
struct CycleWatcher
3037
{
3038
  CycleWatcher(bool& flag)
3039
0
    : Flag(flag)
3040
0
  {
3041
0
    this->Flag = true;
3042
0
  }
3043
0
  ~CycleWatcher() { this->Flag = false; }
3044
  bool& Flag;
3045
};
3046
3047
cmGeneratorTarget const* cmGeneratorTarget::GetPchReuseTarget() const
3048
0
{
3049
0
  if (this->ComputingPchReuse) {
3050
    // TODO: Get the full cycle.
3051
0
    if (!this->PchReuseCycleDetected) {
3052
0
      this->Makefile->IssueMessage(
3053
0
        MessageType::FATAL_ERROR,
3054
0
        cmStrCat("Circular PCH reuse target involving '", this->GetName(),
3055
0
                 '\''));
3056
0
    }
3057
0
    this->PchReuseCycleDetected = true;
3058
0
    return nullptr;
3059
0
  }
3060
0
  CycleWatcher watch(this->ComputingPchReuse);
3061
0
  (void)watch;
3062
0
  cmValue pchReuseFrom = this->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
3063
0
  if (!pchReuseFrom) {
3064
0
    return nullptr;
3065
0
  }
3066
0
  cmGeneratorTarget const* generatorTarget =
3067
0
    this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
3068
0
  if (!generatorTarget) {
3069
0
    this->Makefile->IssueMessage(
3070
0
      MessageType::FATAL_ERROR,
3071
0
      cmStrCat(
3072
0
        "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
3073
0
        R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property does not exist.)"));
3074
0
  }
3075
0
  if (this->GetProperty("PRECOMPILE_HEADERS").IsOn()) {
3076
0
    this->Makefile->IssueMessage(
3077
0
      MessageType::FATAL_ERROR,
3078
0
      cmStrCat("PRECOMPILE_HEADERS property is already set on target (\"",
3079
0
               this->GetName(), "\")\n"));
3080
0
  }
3081
3082
0
  if (generatorTarget) {
3083
0
    if (generatorTarget->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
3084
0
      this->Makefile->IssueMessage(
3085
0
        MessageType::WARNING,
3086
0
        cmStrCat(
3087
0
          "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
3088
0
          R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property has set "DISABLE_PRECOMPILE_HEADERS"; ignoring.)"));
3089
0
      return nullptr;
3090
0
    }
3091
3092
0
    if (auto const* recurseReuseTarget =
3093
0
          generatorTarget->GetPchReuseTarget()) {
3094
0
      return recurseReuseTarget;
3095
0
    }
3096
0
  }
3097
0
  return generatorTarget;
3098
0
}
3099
3100
cmGeneratorTarget* cmGeneratorTarget::GetPchReuseTarget()
3101
0
{
3102
0
  if (this->ComputingPchReuse) {
3103
    // TODO: Get the full cycle.
3104
0
    if (!this->PchReuseCycleDetected) {
3105
0
      this->Makefile->IssueMessage(
3106
0
        MessageType::FATAL_ERROR,
3107
0
        cmStrCat("Circular PCH reuse target involving '", this->GetName(),
3108
0
                 '\''));
3109
0
    }
3110
0
    this->PchReuseCycleDetected = true;
3111
0
    return nullptr;
3112
0
  }
3113
0
  CycleWatcher watch(this->ComputingPchReuse);
3114
0
  (void)watch;
3115
0
  cmValue pchReuseFrom = this->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
3116
0
  if (!pchReuseFrom) {
3117
0
    return nullptr;
3118
0
  }
3119
0
  cmGeneratorTarget* generatorTarget =
3120
0
    this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
3121
0
  if (!generatorTarget) {
3122
0
    this->Makefile->IssueMessage(
3123
0
      MessageType::FATAL_ERROR,
3124
0
      cmStrCat(
3125
0
        "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
3126
0
        R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property does not exist.)"));
3127
0
  }
3128
0
  if (this->GetProperty("PRECOMPILE_HEADERS").IsOn()) {
3129
0
    this->Makefile->IssueMessage(
3130
0
      MessageType::FATAL_ERROR,
3131
0
      cmStrCat("PRECOMPILE_HEADERS property is already set on target (\"",
3132
0
               this->GetName(), "\")\n"));
3133
0
  }
3134
3135
0
  if (generatorTarget) {
3136
0
    if (generatorTarget->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
3137
0
      this->Makefile->IssueMessage(
3138
0
        MessageType::WARNING,
3139
0
        cmStrCat(
3140
0
          "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
3141
0
          R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property has set "DISABLE_PRECOMPILE_HEADERS"; ignoring.)"));
3142
0
      return nullptr;
3143
0
    }
3144
3145
0
    if (auto* recurseReuseTarget = generatorTarget->GetPchReuseTarget()) {
3146
0
      return recurseReuseTarget;
3147
0
    }
3148
0
  }
3149
0
  return generatorTarget;
3150
0
}
3151
3152
std::vector<std::string> cmGeneratorTarget::GetPchArchs(
3153
  std::string const& config, std::string const& lang) const
3154
0
{
3155
0
  std::vector<std::string> pchArchs;
3156
0
  if (!this->GetGlobalGenerator()->IsXcode()) {
3157
0
    pchArchs = this->GetAppleArchs(config, lang);
3158
0
  }
3159
0
  if (pchArchs.size() < 2) {
3160
    // We do not need per-arch PCH files when building for one architecture.
3161
0
    pchArchs = { {} };
3162
0
  }
3163
0
  return pchArchs;
3164
0
}
3165
3166
std::string cmGeneratorTarget::GetPchHeader(std::string const& config,
3167
                                            std::string const& language,
3168
                                            std::string const& arch) const
3169
0
{
3170
0
  if (language != "C" && language != "CXX" && language != "OBJC" &&
3171
0
      language != "OBJCXX") {
3172
0
    return std::string();
3173
0
  }
3174
3175
0
  if (this->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
3176
0
    return std::string();
3177
0
  }
3178
0
  cmGeneratorTarget const* generatorTarget = this;
3179
0
  cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget();
3180
0
  bool const haveReuseTarget = reuseTarget && reuseTarget != this;
3181
0
  if (reuseTarget) {
3182
0
    generatorTarget = reuseTarget;
3183
0
  }
3184
3185
0
  auto const inserted =
3186
0
    this->PchHeaders.insert(std::make_pair(language + config + arch, ""));
3187
0
  if (inserted.second) {
3188
0
    std::vector<BT<std::string>> const headers =
3189
0
      this->GetPrecompileHeaders(config, language);
3190
0
    if (headers.empty() && !haveReuseTarget) {
3191
0
      return std::string();
3192
0
    }
3193
0
    std::string& filename = inserted.first->second;
3194
3195
0
    std::map<std::string, std::string> const languageToExtension = {
3196
0
      { "C", ".h" },
3197
0
      { "CXX", ".hxx" },
3198
0
      { "OBJC", ".objc.h" },
3199
0
      { "OBJCXX", ".objcxx.hxx" }
3200
0
    };
3201
3202
0
    filename = generatorTarget->GetCMFSupportDirectory();
3203
3204
0
    if (this->GetGlobalGenerator()->IsMultiConfig()) {
3205
0
      filename = cmStrCat(filename, '/', config);
3206
0
    }
3207
3208
    // This is acceptable as its the source file, won't have a rename/hash
3209
0
    filename =
3210
0
      cmStrCat(filename, "/cmake_pch", arch.empty() ? "" : cmStrCat('_', arch),
3211
0
               languageToExtension.at(language));
3212
3213
0
    std::string const filename_tmp = cmStrCat(filename, ".tmp");
3214
0
    if (!haveReuseTarget) {
3215
0
      cmValue pchPrologue =
3216
0
        this->Makefile->GetDefinition("CMAKE_PCH_PROLOGUE");
3217
0
      cmValue pchEpilogue =
3218
0
        this->Makefile->GetDefinition("CMAKE_PCH_EPILOGUE");
3219
3220
0
      std::string firstHeaderOnDisk;
3221
0
      {
3222
0
        cmGeneratedFileStream file(
3223
0
          filename_tmp, false,
3224
0
          this->GetGlobalGenerator()->GetMakefileEncoding());
3225
0
        file << "/* generated by CMake */\n\n";
3226
0
        if (pchPrologue) {
3227
0
          file << *pchPrologue << "\n";
3228
0
        }
3229
0
        if (this->GetGlobalGenerator()->IsXcode()) {
3230
0
          file << "#ifndef CMAKE_SKIP_PRECOMPILE_HEADERS\n";
3231
0
        }
3232
0
        if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
3233
0
          file << "#ifdef __cplusplus\n";
3234
0
        }
3235
0
        for (auto const& header_bt : headers) {
3236
0
          if (header_bt.Value.empty()) {
3237
0
            continue;
3238
0
          }
3239
0
          if (header_bt.Value[0] == '<' || header_bt.Value[0] == '\"') {
3240
0
            file << "#include " << header_bt.Value << "\n";
3241
0
          } else {
3242
0
            file << "#include \"" << header_bt.Value << "\"\n";
3243
0
          }
3244
3245
0
          if (cmSystemTools::FileExists(header_bt.Value) &&
3246
0
              firstHeaderOnDisk.empty()) {
3247
0
            firstHeaderOnDisk = header_bt.Value;
3248
0
          }
3249
0
        }
3250
0
        if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
3251
0
          file << "#endif // __cplusplus\n";
3252
0
        }
3253
0
        if (this->GetGlobalGenerator()->IsXcode()) {
3254
0
          file << "#endif // CMAKE_SKIP_PRECOMPILE_HEADERS\n";
3255
0
        }
3256
0
        if (pchEpilogue) {
3257
0
          file << *pchEpilogue << "\n";
3258
0
        }
3259
0
      }
3260
3261
0
      if (!firstHeaderOnDisk.empty()) {
3262
0
        cmFileTimes::Copy(firstHeaderOnDisk, filename_tmp);
3263
0
      }
3264
3265
0
      cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
3266
0
    }
3267
0
  }
3268
0
  return inserted.first->second;
3269
0
}
3270
3271
std::string cmGeneratorTarget::GetPchSource(std::string const& config,
3272
                                            std::string const& language,
3273
                                            std::string const& arch) const
3274
0
{
3275
0
  if (language != "C" && language != "CXX" && language != "OBJC" &&
3276
0
      language != "OBJCXX") {
3277
0
    return std::string();
3278
0
  }
3279
0
  auto const inserted =
3280
0
    this->PchSources.insert(std::make_pair(language + config + arch, ""));
3281
0
  if (inserted.second) {
3282
0
    std::string const pchHeader = this->GetPchHeader(config, language, arch);
3283
0
    if (pchHeader.empty()) {
3284
0
      return std::string();
3285
0
    }
3286
0
    std::string& filename = inserted.first->second;
3287
3288
0
    cmGeneratorTarget const* generatorTarget = this;
3289
0
    cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget();
3290
0
    bool const haveReuseTarget = reuseTarget && reuseTarget != this;
3291
0
    if (reuseTarget) {
3292
0
      generatorTarget = reuseTarget;
3293
0
    }
3294
3295
0
    filename =
3296
0
      cmStrCat(generatorTarget->GetCMFSupportDirectory(), "/cmake_pch");
3297
3298
    // For GCC the source extension will be transformed into .h[xx].gch
3299
0
    if (!this->Makefile->IsOn("CMAKE_LINK_PCH")) {
3300
0
      std::map<std::string, std::string> const languageToExtension = {
3301
0
        { "C", ".h.c" },
3302
0
        { "CXX", ".hxx.cxx" },
3303
0
        { "OBJC", ".objc.h.m" },
3304
0
        { "OBJCXX", ".objcxx.hxx.mm" }
3305
0
      };
3306
3307
0
      filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat('_', arch),
3308
0
                          languageToExtension.at(language));
3309
0
    } else {
3310
0
      std::map<std::string, std::string> const languageToExtension = {
3311
0
        { "C", ".c" }, { "CXX", ".cxx" }, { "OBJC", ".m" }, { "OBJCXX", ".mm" }
3312
0
      };
3313
3314
0
      filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat('_', arch),
3315
0
                          languageToExtension.at(language));
3316
0
    }
3317
3318
0
    std::string const filename_tmp = cmStrCat(filename, ".tmp");
3319
0
    if (!haveReuseTarget) {
3320
0
      {
3321
0
        cmGeneratedFileStream file(filename_tmp);
3322
0
        file << "/* generated by CMake */\n";
3323
0
      }
3324
0
      cmFileTimes::Copy(pchHeader, filename_tmp);
3325
0
      cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
3326
0
    }
3327
0
  }
3328
0
  return inserted.first->second;
3329
0
}
3330
3331
std::string cmGeneratorTarget::GetPchFileObject(std::string const& config,
3332
                                                std::string const& language,
3333
                                                std::string const& arch)
3334
0
{
3335
0
  if (language != "C" && language != "CXX" && language != "OBJC" &&
3336
0
      language != "OBJCXX") {
3337
0
    return std::string();
3338
0
  }
3339
0
  auto const inserted =
3340
0
    this->PchObjectFiles.insert(std::make_pair(language + config + arch, ""));
3341
0
  if (inserted.second) {
3342
0
    std::string const pchSource = this->GetPchSource(config, language, arch);
3343
0
    if (pchSource.empty()) {
3344
0
      return std::string();
3345
0
    }
3346
0
    std::string& filename = inserted.first->second;
3347
3348
0
    auto* pchSf = this->Makefile->GetOrCreateSource(
3349
0
      pchSource, false, cmSourceFileLocationKind::Known);
3350
0
    pchSf->SetSpecialSourceType(cmSourceFile::SpecialSourceType::PchSource);
3351
0
    pchSf->ResolveFullPath();
3352
0
    filename = cmStrCat(this->GetObjectDirectory(config), '/',
3353
0
                        this->GetObjectName(pchSf));
3354
0
  }
3355
0
  return inserted.first->second;
3356
0
}
3357
3358
std::string cmGeneratorTarget::GetPchFile(std::string const& config,
3359
                                          std::string const& language,
3360
                                          std::string const& arch)
3361
0
{
3362
0
  auto const inserted =
3363
0
    this->PchFiles.insert(std::make_pair(language + config + arch, ""));
3364
0
  if (inserted.second) {
3365
0
    std::string& pchFile = inserted.first->second;
3366
3367
0
    std::string const pchExtension =
3368
0
      this->Makefile->GetSafeDefinition("CMAKE_PCH_EXTENSION");
3369
3370
0
    if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
3371
0
      auto replaceExtension = [](std::string const& str,
3372
0
                                 std::string const& ext) -> std::string {
3373
0
        auto dot_pos = str.rfind('.');
3374
0
        std::string result;
3375
0
        if (dot_pos != std::string::npos) {
3376
0
          result = str.substr(0, dot_pos);
3377
0
        }
3378
0
        result += ext;
3379
0
        return result;
3380
0
      };
3381
3382
0
      cmGeneratorTarget* generatorTarget = this;
3383
0
      cmGeneratorTarget* reuseTarget = this->GetPchReuseTarget();
3384
0
      if (reuseTarget) {
3385
0
        generatorTarget = reuseTarget;
3386
0
      }
3387
3388
0
      std::string const pchFileObject =
3389
0
        generatorTarget->GetPchFileObject(config, language, arch);
3390
0
      if (!pchExtension.empty()) {
3391
0
        pchFile = replaceExtension(pchFileObject, pchExtension);
3392
0
      }
3393
0
    } else {
3394
0
      if (this->GetUseShortObjectNames() && !pchExtension.empty()) {
3395
0
        auto pchSource = this->GetPchSource(config, language, arch);
3396
0
        auto* pchSf = this->Makefile->GetOrCreateSource(
3397
0
          pchSource, false, cmSourceFileLocationKind::Known);
3398
0
        pchSf->SetSpecialSourceType(
3399
0
          cmSourceFile::SpecialSourceType::PchSource);
3400
0
        pchSf->ResolveFullPath();
3401
0
        std::string cfgSubdir;
3402
0
        if (this->GetGlobalGenerator()->IsMultiConfig()) {
3403
0
          cfgSubdir = cmStrCat(config, '/');
3404
0
        }
3405
0
        pchFile = cmStrCat(
3406
0
          this->GetSupportDirectory(), '/', cfgSubdir,
3407
0
          this->LocalGenerator->GetShortObjectFileName(*pchSf), pchExtension);
3408
0
      } else {
3409
0
        pchFile =
3410
0
          cmStrCat(this->GetPchHeader(config, language, arch), pchExtension);
3411
0
      }
3412
0
    }
3413
0
  }
3414
0
  return inserted.first->second;
3415
0
}
3416
3417
std::string cmGeneratorTarget::GetPchCreateCompileOptions(
3418
  std::string const& config, std::string const& language,
3419
  std::string const& arch)
3420
0
{
3421
0
  auto const inserted = this->PchCreateCompileOptions.insert(
3422
0
    std::make_pair(language + config + arch, ""));
3423
0
  if (inserted.second) {
3424
0
    std::string& createOptionList = inserted.first->second;
3425
3426
0
    if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
3427
0
      createOptionList = this->Makefile->GetSafeDefinition(
3428
0
        cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
3429
0
    }
3430
3431
0
    if (this->GetPropertyAsBool("PCH_INSTANTIATE_TEMPLATES")) {
3432
0
      std::string varName = cmStrCat(
3433
0
        "CMAKE_", language, "_COMPILE_OPTIONS_INSTANTIATE_TEMPLATES_PCH");
3434
0
      std::string instantiateOption =
3435
0
        this->Makefile->GetSafeDefinition(varName);
3436
0
      if (!instantiateOption.empty()) {
3437
0
        createOptionList = cmStrCat(createOptionList, ';', instantiateOption);
3438
0
      }
3439
0
    }
3440
3441
0
    std::string const createOptVar =
3442
0
      cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_CREATE_PCH");
3443
3444
0
    createOptionList = cmStrCat(
3445
0
      createOptionList, ';', this->Makefile->GetSafeDefinition(createOptVar));
3446
3447
0
    std::string const pchHeader = this->GetPchHeader(config, language, arch);
3448
0
    std::string const pchFile = this->GetPchFile(config, language, arch);
3449
3450
0
    if (GlobalGenerator->IsFastbuild()) {
3451
      // Account for potential spaces in a shell-friendly way.
3452
0
      cmSystemTools::ReplaceString(createOptionList, "<PCH_HEADER>",
3453
0
                                   cmStrCat('"', pchHeader, '"'));
3454
0
      cmSystemTools::ReplaceString(createOptionList, "<PCH_FILE>",
3455
0
                                   cmStrCat('"', pchFile, '"'));
3456
0
    } else {
3457
0
      cmSystemTools::ReplaceString(createOptionList, "<PCH_HEADER>",
3458
0
                                   pchHeader);
3459
0
      cmSystemTools::ReplaceString(createOptionList, "<PCH_FILE>", pchFile);
3460
0
    }
3461
0
  }
3462
0
  return inserted.first->second;
3463
0
}
3464
3465
std::string cmGeneratorTarget::GetPchUseCompileOptions(
3466
  std::string const& config, std::string const& language,
3467
  std::string const& arch)
3468
0
{
3469
0
  auto const inserted = this->PchUseCompileOptions.insert(
3470
0
    std::make_pair(language + config + arch, ""));
3471
0
  if (inserted.second) {
3472
0
    std::string& useOptionList = inserted.first->second;
3473
3474
0
    if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
3475
0
      useOptionList = this->Makefile->GetSafeDefinition(
3476
0
        cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
3477
0
    }
3478
3479
0
    std::string const useOptVar =
3480
0
      cmStrCat(language, "_COMPILE_OPTIONS_USE_PCH");
3481
3482
0
    std::string const& useOptionListProperty =
3483
0
      this->GetSafeProperty(useOptVar);
3484
3485
0
    useOptionList = cmStrCat(
3486
0
      useOptionList, ';',
3487
0
      useOptionListProperty.empty()
3488
0
        ? this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_", useOptVar))
3489
0
        : useOptionListProperty);
3490
3491
0
    std::string const pchHeader = this->GetPchHeader(config, language, arch);
3492
0
    std::string const pchFile = this->GetPchFile(config, language, arch);
3493
3494
0
    if (GlobalGenerator->IsFastbuild()) {
3495
      // Account for potential spaces in a shell-friendly way.
3496
0
      cmSystemTools::ReplaceString(useOptionList, "<PCH_HEADER>",
3497
0
                                   cmStrCat('"', pchHeader, '"'));
3498
0
      cmSystemTools::ReplaceString(useOptionList, "<PCH_FILE>",
3499
0
                                   cmStrCat('"', pchFile, '"'));
3500
0
    } else {
3501
0
      cmSystemTools::ReplaceString(useOptionList, "<PCH_HEADER>", pchHeader);
3502
0
      cmSystemTools::ReplaceString(useOptionList, "<PCH_FILE>", pchFile);
3503
0
    }
3504
0
  }
3505
0
  return inserted.first->second;
3506
0
}
3507
3508
void cmGeneratorTarget::AddSourceFileToUnityBatch(
3509
  std::string const& sourceFilename)
3510
0
{
3511
0
  this->UnityBatchedSourceFiles.insert(sourceFilename);
3512
0
}
3513
3514
bool cmGeneratorTarget::IsSourceFilePartOfUnityBatch(
3515
  std::string const& sourceFilename) const
3516
0
{
3517
0
  if (!this->GetPropertyAsBool("UNITY_BUILD")) {
3518
0
    return false;
3519
0
  }
3520
3521
0
  return this->UnityBatchedSourceFiles.find(sourceFilename) !=
3522
0
    this->UnityBatchedSourceFiles.end();
3523
0
}
3524
3525
void cmGeneratorTarget::ComputeTargetManifest(std::string const& config) const
3526
0
{
3527
0
  if (this->IsImported()) {
3528
0
    return;
3529
0
  }
3530
0
  cmGlobalGenerator* gg = this->LocalGenerator->GetGlobalGenerator();
3531
3532
  // Get the names.
3533
0
  cmGeneratorTarget::Names targetNames;
3534
0
  if (this->GetType() == cm::TargetType::EXECUTABLE) {
3535
0
    targetNames = this->GetExecutableNames(config);
3536
0
  } else if (this->GetType() == cm::TargetType::STATIC_LIBRARY ||
3537
0
             this->GetType() == cm::TargetType::SHARED_LIBRARY ||
3538
0
             this->GetType() == cm::TargetType::MODULE_LIBRARY) {
3539
0
    targetNames = this->GetLibraryNames(config);
3540
0
  } else {
3541
0
    return;
3542
0
  }
3543
3544
  // Get the directory.
3545
0
  std::string dir =
3546
0
    this->GetDirectory(config, cmStateEnums::RuntimeBinaryArtifact);
3547
3548
  // Add each name.
3549
0
  std::string f;
3550
0
  if (!targetNames.Output.empty()) {
3551
0
    f = cmStrCat(dir, '/', targetNames.Output);
3552
0
    gg->AddToManifest(f);
3553
0
  }
3554
0
  if (!targetNames.SharedObject.empty()) {
3555
0
    f = cmStrCat(dir, '/', targetNames.SharedObject);
3556
0
    gg->AddToManifest(f);
3557
0
  }
3558
0
  if (!targetNames.Real.empty()) {
3559
0
    f = cmStrCat(dir, '/', targetNames.Real);
3560
0
    gg->AddToManifest(f);
3561
0
  }
3562
0
  if (!targetNames.PDB.empty()) {
3563
0
    f = cmStrCat(dir, '/', targetNames.PDB);
3564
0
    gg->AddToManifest(f);
3565
0
  }
3566
3567
0
  dir = this->GetDirectory(config, cmStateEnums::ImportLibraryArtifact);
3568
0
  if (!targetNames.ImportOutput.empty()) {
3569
0
    f = cmStrCat(dir, '/', targetNames.ImportOutput);
3570
0
    gg->AddToManifest(f);
3571
0
  }
3572
0
  if (!targetNames.ImportLibrary.empty()) {
3573
0
    f = cmStrCat(dir, '/', targetNames.ImportLibrary);
3574
0
    gg->AddToManifest(f);
3575
0
  }
3576
0
  if (!targetNames.ImportReal.empty()) {
3577
0
    f = cmStrCat(dir, '/', targetNames.ImportReal);
3578
0
    gg->AddToManifest(f);
3579
0
  }
3580
0
}
3581
3582
cm::optional<cmStandardLevel> cmGeneratorTarget::GetExplicitStandardLevel(
3583
  std::string const& lang, std::string const& config) const
3584
0
{
3585
0
  cm::optional<cmStandardLevel> level;
3586
0
  std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
3587
0
  auto i = this->ExplicitStandardLevel.find(key);
3588
0
  if (i != this->ExplicitStandardLevel.end()) {
3589
0
    level = i->second;
3590
0
  }
3591
0
  return level;
3592
0
}
3593
3594
void cmGeneratorTarget::UpdateExplicitStandardLevel(std::string const& lang,
3595
                                                    std::string const& config,
3596
                                                    cmStandardLevel level)
3597
0
{
3598
0
  auto e = this->ExplicitStandardLevel.emplace(
3599
0
    cmStrCat(cmSystemTools::UpperCase(config), '-', lang), level);
3600
0
  if (!e.second && e.first->second < level) {
3601
0
    e.first->second = level;
3602
0
  }
3603
0
}
3604
3605
bool cmGeneratorTarget::ComputeCompileFeatures(std::string const& config)
3606
0
{
3607
0
  cmStandardLevelResolver standardResolver(this->Makefile);
3608
3609
0
  for (std::string const& lang :
3610
0
       this->Makefile->GetState()->GetEnabledLanguages()) {
3611
0
    if (cmValue languageStd = this->GetLanguageStandard(lang, config)) {
3612
0
      if (cm::optional<cmStandardLevel> langLevel =
3613
0
            standardResolver.LanguageStandardLevel(lang, *languageStd)) {
3614
0
        this->UpdateExplicitStandardLevel(lang, config, *langLevel);
3615
0
      }
3616
0
    }
3617
0
  }
3618
3619
  // Compute the language standard based on the compile features.
3620
0
  std::vector<BT<std::string>> features = this->GetCompileFeatures(config);
3621
0
  for (BT<std::string> const& f : features) {
3622
0
    std::string lang;
3623
0
    if (!standardResolver.CompileFeatureKnown(this->Target->GetName(), f.Value,
3624
0
                                              lang, nullptr)) {
3625
0
      return false;
3626
0
    }
3627
3628
0
    std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
3629
0
    cmValue currentLanguageStandard = this->GetLanguageStandard(lang, config);
3630
3631
0
    cm::optional<cmStandardLevel> featureLevel;
3632
0
    std::string newRequiredStandard;
3633
0
    if (!standardResolver.GetNewRequiredStandard(
3634
0
          this->Target->GetName(), f.Value, currentLanguageStandard,
3635
0
          featureLevel, newRequiredStandard)) {
3636
0
      return false;
3637
0
    }
3638
3639
0
    if (featureLevel) {
3640
0
      this->UpdateExplicitStandardLevel(lang, config, *featureLevel);
3641
0
    }
3642
3643
0
    if (!newRequiredStandard.empty()) {
3644
0
      BTs<std::string>& languageStandardProperty =
3645
0
        this->LanguageStandardMap[key];
3646
0
      if (languageStandardProperty.Value != newRequiredStandard) {
3647
0
        languageStandardProperty.Value = newRequiredStandard;
3648
0
        languageStandardProperty.Backtraces.clear();
3649
0
      }
3650
0
      languageStandardProperty.Backtraces.emplace_back(f.Backtrace);
3651
0
    }
3652
0
  }
3653
3654
0
  return true;
3655
0
}
3656
3657
bool cmGeneratorTarget::ComputeCompileFeatures(
3658
  std::string const& config, std::set<LanguagePair> const& languagePairs)
3659
0
{
3660
0
  for (auto const& language : languagePairs) {
3661
0
    BTs<std::string> const* generatorTargetLanguageStandard =
3662
0
      this->GetLanguageStandardProperty(language.first, config);
3663
0
    if (!generatorTargetLanguageStandard) {
3664
      // If the standard isn't explicitly set we copy it over from the
3665
      // specified paired language.
3666
0
      std::string key =
3667
0
        cmStrCat(cmSystemTools::UpperCase(config), '-', language.first);
3668
0
      BTs<std::string> const* standardToCopy =
3669
0
        this->GetLanguageStandardProperty(language.second, config);
3670
0
      if (standardToCopy) {
3671
0
        this->LanguageStandardMap[key] = *standardToCopy;
3672
0
        generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
3673
0
      } else {
3674
0
        cmValue defaultStandard = this->Makefile->GetDefinition(
3675
0
          cmStrCat("CMAKE_", language.second, "_STANDARD_DEFAULT"));
3676
0
        if (defaultStandard) {
3677
0
          this->LanguageStandardMap[key] = BTs<std::string>(*defaultStandard);
3678
0
          generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
3679
0
        }
3680
0
      }
3681
3682
      // Custom updates for the CUDA standard.
3683
0
      if (generatorTargetLanguageStandard && (language.first == "CUDA")) {
3684
0
        if (generatorTargetLanguageStandard->Value == "98") {
3685
0
          this->LanguageStandardMap[key].Value = "03";
3686
0
        }
3687
0
      }
3688
0
    }
3689
0
  }
3690
3691
0
  return true;
3692
0
}
3693
3694
std::string cmGeneratorTarget::GetImportedLibName(
3695
  std::string const& config) const
3696
0
{
3697
0
  if (cmGeneratorTarget::ImportInfo const* info =
3698
0
        this->GetImportInfo(config)) {
3699
0
    return info->LibName;
3700
0
  }
3701
0
  return std::string();
3702
0
}
3703
3704
std::string cmGeneratorTarget::GetFullPath(std::string const& config,
3705
                                           cmStateEnums::ArtifactType artifact,
3706
                                           bool realname) const
3707
0
{
3708
0
  if (this->IsImported()) {
3709
0
    return this->Target->ImportedGetFullPath(config, artifact);
3710
0
  }
3711
0
  return this->NormalGetFullPath(config, artifact, realname);
3712
0
}
3713
3714
std::string cmGeneratorTarget::NormalGetFullPath(
3715
  std::string const& config, cmStateEnums::ArtifactType artifact,
3716
  bool realname) const
3717
0
{
3718
0
  std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/');
3719
0
  if (this->IsAppBundleOnApple()) {
3720
0
    fpath =
3721
0
      cmStrCat(this->BuildBundleDirectory(fpath, config, FullLevel), '/');
3722
0
  }
3723
3724
  // Add the full name of the target.
3725
0
  switch (artifact) {
3726
0
    case cmStateEnums::RuntimeBinaryArtifact:
3727
0
      if (realname) {
3728
0
        fpath += this->NormalGetRealName(config);
3729
0
      } else {
3730
0
        fpath +=
3731
0
          this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact);
3732
0
      }
3733
0
      break;
3734
0
    case cmStateEnums::ImportLibraryArtifact:
3735
0
      if (realname) {
3736
0
        fpath +=
3737
0
          this->NormalGetRealName(config, cmStateEnums::ImportLibraryArtifact);
3738
0
      } else {
3739
0
        fpath +=
3740
0
          this->GetFullName(config, cmStateEnums::ImportLibraryArtifact);
3741
0
      }
3742
0
      break;
3743
0
  }
3744
0
  return fpath;
3745
0
}
3746
3747
std::string cmGeneratorTarget::NormalGetRealName(
3748
  std::string const& config, cmStateEnums::ArtifactType artifact) const
3749
0
{
3750
  // This should not be called for imported targets.
3751
  // TODO: Split cmTarget into a class hierarchy to get compile-time
3752
  // enforcement of the limited imported target API.
3753
0
  if (this->IsImported()) {
3754
0
    std::string msg = cmStrCat("NormalGetRealName called on imported target: ",
3755
0
                               this->GetName());
3756
0
    this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
3757
0
  }
3758
3759
0
  Names names = this->GetType() == cm::TargetType::EXECUTABLE
3760
0
    ? this->GetExecutableNames(config)
3761
0
    : this->GetLibraryNames(config);
3762
3763
  // Compute the real name that will be built.
3764
0
  return artifact == cmStateEnums::RuntimeBinaryArtifact ? names.Real
3765
0
                                                         : names.ImportReal;
3766
0
}
3767
3768
cmGeneratorTarget::Names cmGeneratorTarget::GetLibraryNames(
3769
  std::string const& config) const
3770
0
{
3771
0
  cmGeneratorTarget::Names targetNames;
3772
3773
  // This should not be called for imported targets.
3774
  // TODO: Split cmTarget into a class hierarchy to get compile-time
3775
  // enforcement of the limited imported target API.
3776
0
  if (this->IsImported()) {
3777
0
    std::string msg =
3778
0
      cmStrCat("GetLibraryNames called on imported target: ", this->GetName());
3779
0
    this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
3780
0
  }
3781
3782
  // Check for library version properties.
3783
0
  cmValue version = this->GetProperty("VERSION");
3784
0
  cmValue soversion = this->GetProperty("SOVERSION");
3785
0
  if (!this->HasSOName(config) ||
3786
0
      this->Makefile->IsOn("CMAKE_PLATFORM_NO_VERSIONED_SONAME") ||
3787
0
      this->IsFrameworkOnApple()) {
3788
    // Versioning is supported only for shared libraries and modules,
3789
    // and then only when the platform supports an soname flag.
3790
0
    version = nullptr;
3791
0
    soversion = nullptr;
3792
0
  }
3793
0
  if (version && !soversion) {
3794
    // The soversion must be set if the library version is set.  Use
3795
    // the library version as the soversion.
3796
0
    soversion = version;
3797
0
  }
3798
0
  if (!version && soversion) {
3799
    // Use the soversion as the library version.
3800
0
    version = soversion;
3801
0
  }
3802
3803
  // Get the components of the library name.
3804
0
  NameComponents const& components = this->GetFullNameInternalComponents(
3805
0
    config, cmStateEnums::RuntimeBinaryArtifact);
3806
3807
  // The library name.
3808
0
  targetNames.Base = components.base;
3809
0
  targetNames.Output =
3810
0
    cmStrCat(components.prefix, targetNames.Base, components.suffix);
3811
3812
0
  if (this->IsFrameworkOnApple()) {
3813
0
    targetNames.Real = components.prefix;
3814
0
    if (!this->Makefile->PlatformIsAppleEmbedded()) {
3815
0
      targetNames.Real = cmStrCat(std::move(targetNames.Real), "Versions/",
3816
0
                                  this->GetFrameworkVersion(), '/');
3817
0
    }
3818
0
    targetNames.Real = cmStrCat(std::move(targetNames.Real), targetNames.Base,
3819
0
                                components.suffix);
3820
0
    targetNames.SharedObject = targetNames.Real;
3821
0
  } else if (this->IsArchivedAIXSharedLibrary()) {
3822
0
    targetNames.SharedObject =
3823
0
      cmStrCat(components.prefix, targetNames.Base, ".so");
3824
0
    if (soversion) {
3825
0
      targetNames.SharedObject =
3826
0
        cmStrCat(std::move(targetNames.SharedObject), '.', *soversion);
3827
0
    }
3828
0
    targetNames.Real = targetNames.Output;
3829
0
  } else {
3830
    // The library's soname.
3831
0
    targetNames.SharedObject = this->ComputeVersionedName(
3832
0
      components.prefix, targetNames.Base, components.suffix,
3833
0
      targetNames.Output, soversion);
3834
3835
    // The library's real name on disk.
3836
0
    targetNames.Real = this->ComputeVersionedName(
3837
0
      components.prefix, targetNames.Base, components.suffix,
3838
0
      targetNames.Output, version);
3839
0
  }
3840
3841
  // The import library names.
3842
0
  if (this->GetType() == cm::TargetType::SHARED_LIBRARY ||
3843
0
      this->GetType() == cm::TargetType::MODULE_LIBRARY) {
3844
0
    NameComponents const& importComponents =
3845
0
      this->GetFullNameInternalComponents(config,
3846
0
                                          cmStateEnums::ImportLibraryArtifact);
3847
0
    targetNames.ImportOutput = cmStrCat(
3848
0
      importComponents.prefix, importComponents.base, importComponents.suffix);
3849
3850
0
    if (this->IsFrameworkOnApple() && this->IsSharedLibraryWithExports()) {
3851
0
      targetNames.ImportReal = components.prefix;
3852
0
      if (!this->Makefile->PlatformIsAppleEmbedded()) {
3853
0
        targetNames.ImportReal =
3854
0
          cmStrCat(std::move(targetNames.ImportReal), "Versions/",
3855
0
                   this->GetFrameworkVersion(), '/');
3856
0
      }
3857
0
      targetNames.ImportReal =
3858
0
        cmStrCat(std::move(targetNames.ImportReal), importComponents.base,
3859
0
                 importComponents.suffix);
3860
0
      targetNames.ImportLibrary = targetNames.ImportOutput;
3861
0
    } else {
3862
      // The import library's soname.
3863
0
      targetNames.ImportLibrary = this->ComputeVersionedName(
3864
0
        importComponents.prefix, importComponents.base,
3865
0
        importComponents.suffix, targetNames.ImportOutput, soversion);
3866
3867
      // The import library's real name on disk.
3868
0
      targetNames.ImportReal = this->ComputeVersionedName(
3869
0
        importComponents.prefix, importComponents.base,
3870
0
        importComponents.suffix, targetNames.ImportOutput, version);
3871
0
    }
3872
0
  }
3873
3874
  // The program database file name.
3875
0
  targetNames.PDB = this->GetPDBName(config);
3876
3877
0
  return targetNames;
3878
0
}
3879
3880
cmGeneratorTarget::Names cmGeneratorTarget::GetExecutableNames(
3881
  std::string const& config) const
3882
0
{
3883
0
  cmGeneratorTarget::Names targetNames;
3884
3885
  // This should not be called for imported targets.
3886
  // TODO: Split cmTarget into a class hierarchy to get compile-time
3887
  // enforcement of the limited imported target API.
3888
0
  if (this->IsImported()) {
3889
0
    std::string msg = cmStrCat(
3890
0
      "GetExecutableNames called on imported target: ", this->GetName());
3891
0
    this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
3892
0
  }
3893
3894
// This versioning is supported only for executables and then only
3895
// when the platform supports symbolic links.
3896
#if defined(_WIN32) && !defined(__CYGWIN__)
3897
  cmValue version;
3898
#else
3899
  // Check for executable version properties.
3900
0
  cmValue version = this->GetProperty("VERSION");
3901
0
  if (this->GetType() != cm::TargetType::EXECUTABLE ||
3902
0
      this->Makefile->IsOn("XCODE")) {
3903
0
    version = nullptr;
3904
0
  }
3905
0
#endif
3906
3907
  // Get the components of the executable name.
3908
0
  NameComponents const& components = this->GetFullNameInternalComponents(
3909
0
    config, cmStateEnums::RuntimeBinaryArtifact);
3910
3911
  // The executable name.
3912
0
  targetNames.Base = components.base;
3913
3914
0
  if (this->IsArchivedAIXSharedLibrary()) {
3915
0
    targetNames.Output = components.prefix + targetNames.Base;
3916
0
  } else {
3917
0
    targetNames.Output =
3918
0
      components.prefix + targetNames.Base + components.suffix;
3919
0
  }
3920
3921
// The executable's real name on disk.
3922
#if defined(__CYGWIN__)
3923
  targetNames.Real = components.prefix + targetNames.Base;
3924
#else
3925
0
  targetNames.Real = targetNames.Output;
3926
0
#endif
3927
0
  if (version) {
3928
0
    targetNames.Real = cmStrCat(std::move(targetNames.Real), '-', *version);
3929
0
  }
3930
#if defined(__CYGWIN__)
3931
  targetNames.Real += components.suffix;
3932
#endif
3933
3934
  // The import library name.
3935
0
  targetNames.ImportLibrary =
3936
0
    this->GetFullNameInternal(config, cmStateEnums::ImportLibraryArtifact);
3937
0
  targetNames.ImportReal = targetNames.ImportLibrary;
3938
0
  targetNames.ImportOutput = targetNames.ImportLibrary;
3939
3940
  // The program database file name.
3941
0
  targetNames.PDB = this->GetPDBName(config);
3942
3943
0
  return targetNames;
3944
0
}
3945
3946
std::string cmGeneratorTarget::GetFullNameInternal(
3947
  std::string const& config, cmStateEnums::ArtifactType artifact) const
3948
0
{
3949
0
  NameComponents const& components =
3950
0
    this->GetFullNameInternalComponents(config, artifact);
3951
0
  return components.prefix + components.base + components.suffix;
3952
0
}
3953
3954
std::string cmGeneratorTarget::ImportedGetLocation(
3955
  std::string const& config) const
3956
0
{
3957
0
  assert(this->IsImported());
3958
0
  return this->Target->ImportedGetFullPath(
3959
0
    config, cmStateEnums::RuntimeBinaryArtifact);
3960
0
}
3961
3962
std::string cmGeneratorTarget::GetFullNameImported(
3963
  std::string const& config, cmStateEnums::ArtifactType artifact) const
3964
0
{
3965
0
  return cmSystemTools::GetFilenameName(
3966
0
    this->Target->ImportedGetFullPath(config, artifact));
3967
0
}
3968
3969
cmGeneratorTarget::NameComponents const&
3970
cmGeneratorTarget::GetFullNameInternalComponents(
3971
  std::string const& config, cmStateEnums::ArtifactType artifact) const
3972
0
{
3973
0
  assert(artifact == cmStateEnums::RuntimeBinaryArtifact ||
3974
0
         artifact == cmStateEnums::ImportLibraryArtifact);
3975
0
  FullNameCache& cache = artifact == cmStateEnums::RuntimeBinaryArtifact
3976
0
    ? RuntimeBinaryFullNameCache
3977
0
    : ImportLibraryFullNameCache;
3978
0
  auto search = cache.find(config);
3979
0
  if (search != cache.end()) {
3980
0
    return search->second;
3981
0
  }
3982
  // Use just the target name for non-main target types.
3983
0
  if (this->GetType() != cm::TargetType::STATIC_LIBRARY &&
3984
0
      this->GetType() != cm::TargetType::SHARED_LIBRARY &&
3985
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
3986
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
3987
0
    NameComponents components;
3988
0
    components.base = this->GetName();
3989
0
    return cache.emplace(config, std::move(components)).first->second;
3990
0
  }
3991
3992
0
  bool const isImportedLibraryArtifact =
3993
0
    (artifact == cmStateEnums::ImportLibraryArtifact);
3994
3995
  // Return an empty name for the import library if this platform
3996
  // does not support import libraries.
3997
0
  if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
3998
0
    return cache.emplace(config, NameComponents()).first->second;
3999
0
  }
4000
4001
0
  NameComponents parts;
4002
0
  std::string& outPrefix = parts.prefix;
4003
0
  std::string& outBase = parts.base;
4004
0
  std::string& outSuffix = parts.suffix;
4005
4006
  // retrieve prefix and suffix
4007
0
  std::string ll = this->GetLinkerLanguage(config);
4008
0
  cmValue targetPrefix = this->GetFilePrefixInternal(config, artifact, ll);
4009
0
  cmValue targetSuffix = this->GetFileSuffixInternal(config, artifact, ll);
4010
4011
  // The implib option is only allowed for shared libraries, module
4012
  // libraries, and executables.
4013
0
  if (this->GetType() != cm::TargetType::SHARED_LIBRARY &&
4014
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY &&
4015
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
4016
0
    artifact = cmStateEnums::RuntimeBinaryArtifact;
4017
0
  }
4018
4019
  // Compute the full name for main target types.
4020
0
  std::string configPostfix = this->GetFilePostfix(config);
4021
4022
  // frameworks have directory prefix
4023
0
  std::string fw_prefix;
4024
0
  if (this->IsFrameworkOnApple()) {
4025
0
    fw_prefix =
4026
0
      cmStrCat(this->GetFrameworkDirectory(config, ContentLevel), '/');
4027
0
    targetPrefix = cmValue(fw_prefix);
4028
0
    if (!isImportedLibraryArtifact) {
4029
      // no suffix
4030
0
      targetSuffix = nullptr;
4031
0
    }
4032
0
  }
4033
4034
0
  if (this->IsCFBundleOnApple()) {
4035
0
    fw_prefix = cmStrCat(this->GetCFBundleDirectory(config, FullLevel), '/');
4036
0
    targetPrefix = cmValue(fw_prefix);
4037
0
    targetSuffix = nullptr;
4038
0
  }
4039
4040
  // Begin the final name with the prefix.
4041
0
  outPrefix = targetPrefix ? *targetPrefix : "";
4042
4043
  // Append the target name or property-specified name.
4044
0
  outBase += this->GetOutputName(config, artifact);
4045
4046
  // Append the per-configuration postfix.
4047
  // When using Xcode, the postfix should be part of the suffix rather than
4048
  // the base, because the suffix ends up being used in Xcode's
4049
  // EXECUTABLE_SUFFIX attribute.
4050
0
  if (this->IsFrameworkOnApple() && this->GetGlobalGenerator()->IsXcode()) {
4051
0
    configPostfix += *targetSuffix;
4052
0
    targetSuffix = cmValue(configPostfix);
4053
0
  } else {
4054
0
    outBase += configPostfix;
4055
0
  }
4056
4057
  // Name shared libraries with their version number on some platforms.
4058
0
  if (cmValue soversion = this->GetProperty("SOVERSION")) {
4059
0
    cmValue dllProp;
4060
0
    if (this->IsDLLPlatform()) {
4061
0
      dllProp = this->GetProperty("DLL_NAME_WITH_SOVERSION");
4062
0
    }
4063
0
    if (this->GetType() == cm::TargetType::SHARED_LIBRARY &&
4064
0
        !isImportedLibraryArtifact &&
4065
0
        (dllProp.IsOn() ||
4066
0
         (!dllProp.IsSet() &&
4067
0
          this->Makefile->IsOn("CMAKE_SHARED_LIBRARY_NAME_WITH_VERSION")))) {
4068
0
      outBase = cmStrCat(std::move(outBase), '-', *soversion);
4069
0
    }
4070
0
  }
4071
4072
  // Append the suffix.
4073
0
  outSuffix = targetSuffix ? *targetSuffix : "";
4074
4075
0
  return cache.emplace(config, std::move(parts)).first->second;
4076
0
}
4077
4078
std::string cmGeneratorTarget::GetLinkerLanguage(
4079
  std::string const& config) const
4080
0
{
4081
0
  return this->GetLinkClosure(config)->LinkerLanguage;
4082
0
}
4083
4084
std::string cmGeneratorTarget::GetLinkerTool(std::string const& config) const
4085
0
{
4086
0
  return this->GetLinkerTool(this->GetLinkerLanguage(config), config);
4087
0
}
4088
4089
std::string cmGeneratorTarget::GetLinkerTool(std::string const& lang,
4090
                                             std::string const& config) const
4091
0
{
4092
0
  auto linkMode = cmStrCat(
4093
0
    "CMAKE_", lang, this->IsDeviceLink() ? "_DEVICE_" : "_", "LINK_MODE");
4094
0
  auto mode = this->Makefile->GetDefinition(linkMode);
4095
0
  if (!mode || mode != "LINKER"_s) {
4096
0
    return this->Makefile->GetDefinition("CMAKE_LINKER");
4097
0
  }
4098
4099
0
  auto linkerType = this->GetLinkerTypeProperty(lang, config);
4100
0
  if (linkerType.empty()) {
4101
0
    linkerType = "DEFAULT";
4102
0
  }
4103
0
  auto usingLinker =
4104
0
    cmStrCat("CMAKE_", lang, "_USING_", this->IsDeviceLink() ? "DEVICE_" : "",
4105
0
             "LINKER_", linkerType);
4106
0
  auto linkerTool = this->Makefile->GetDefinition(usingLinker);
4107
4108
0
  if (!linkerTool) {
4109
0
    if (this->GetGlobalGenerator()->IsVisualStudio() &&
4110
0
        linkerType == "DEFAULT"_s) {
4111
0
      return std::string{};
4112
0
    }
4113
4114
    // fall-back to generic definition
4115
0
    linkerTool = this->Makefile->GetDefinition("CMAKE_LINKER");
4116
4117
0
    if (linkerType != "DEFAULT"_s) {
4118
0
      auto isCMakeLinkerType = [](std::string const& type) -> bool {
4119
0
        return std::all_of(type.cbegin(), type.cend(), cmsysString_isupper);
4120
0
      };
4121
0
      if (isCMakeLinkerType(linkerType)) {
4122
0
        this->LocalGenerator->IssueMessage(
4123
0
          MessageType::FATAL_ERROR,
4124
0
          cmStrCat("LINKER_TYPE '", linkerType,
4125
0
                   "' is unknown or not supported by this toolchain."));
4126
0
      } else {
4127
0
        this->LocalGenerator->IssueMessage(
4128
0
          MessageType::FATAL_ERROR,
4129
0
          cmStrCat("LINKER_TYPE '", linkerType,
4130
0
                   "' is unknown. Did you forget to define the '", usingLinker,
4131
0
                   "' variable?"));
4132
0
      }
4133
0
    }
4134
0
  }
4135
4136
0
  return linkerTool;
4137
0
}
4138
4139
bool cmGeneratorTarget::LinkerEnforcesNoAllowShLibUndefined(
4140
  std::string const& config) const
4141
0
{
4142
  // FIXME(#25486): Account for the LINKER_TYPE target property.
4143
  // Also factor out the hard-coded list below into a platform
4144
  // information table based on the linker id.
4145
0
  std::string ll = this->GetLinkerLanguage(config);
4146
0
  std::string linkerIdVar = cmStrCat("CMAKE_", ll, "_COMPILER_LINKER_ID");
4147
0
  cmValue linkerId = this->Makefile->GetDefinition(linkerIdVar);
4148
  // The GNU bfd-based linker may enforce '--no-allow-shlib-undefined'
4149
  // recursively by default.  The Solaris linker has similar behavior.
4150
0
  return linkerId && (*linkerId == "GNU" || *linkerId == "Solaris");
4151
0
}
4152
4153
std::string cmGeneratorTarget::GetPDBOutputName(
4154
  std::string const& config) const
4155
0
{
4156
  // Lookup/compute/cache the pdb output name for this configuration.
4157
0
  auto i = this->PdbOutputNameMap.find(config);
4158
0
  if (i == this->PdbOutputNameMap.end()) {
4159
    // Add empty name in map to detect potential recursion.
4160
0
    PdbOutputNameMapType::value_type entry(config, "");
4161
0
    i = this->PdbOutputNameMap.insert(entry).first;
4162
4163
    // Compute output name.
4164
0
    std::vector<std::string> props;
4165
0
    std::string configUpper = cmSystemTools::UpperCase(config);
4166
0
    if (!configUpper.empty()) {
4167
      // PDB_NAME_<CONFIG>
4168
0
      props.push_back("PDB_NAME_" + configUpper);
4169
0
    }
4170
4171
    // PDB_NAME
4172
0
    props.emplace_back("PDB_NAME");
4173
4174
0
    std::string outName;
4175
0
    for (std::string const& p : props) {
4176
0
      if (cmValue outNameProp = this->GetProperty(p)) {
4177
0
        outName = *outNameProp;
4178
0
        break;
4179
0
      }
4180
0
    }
4181
4182
    // Now evaluate genex and update the previously-prepared map entry.
4183
0
    if (outName.empty()) {
4184
0
      i->second = cmStrCat(
4185
0
        this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact),
4186
0
        this->GetPolicyStatusCMP0202() != cmPolicies::NEW
4187
0
          ? this->GetFilePostfix(config)
4188
0
          : "");
4189
0
    } else {
4190
0
      i->second =
4191
0
        cmGeneratorExpression::Evaluate(outName, this->LocalGenerator, config);
4192
0
    }
4193
0
  } else if (i->second.empty()) {
4194
    // An empty map entry indicates we have been called recursively
4195
    // from the above block.
4196
0
    this->LocalGenerator->GetCMakeInstance()->IssueMessage(
4197
0
      MessageType::FATAL_ERROR,
4198
0
      cmStrCat("Target '", this->GetName(), "' PDB_NAME depends on itself."),
4199
0
      this->GetBacktrace());
4200
0
  }
4201
0
  return i->second;
4202
0
}
4203
4204
std::string cmGeneratorTarget::GetPDBName(std::string const& config) const
4205
0
{
4206
0
  NameComponents const& parts = this->GetFullNameInternalComponents(
4207
0
    config, cmStateEnums::RuntimeBinaryArtifact);
4208
4209
0
  std::string base = this->GetPDBOutputName(config);
4210
4211
0
  return cmStrCat(parts.prefix, base,
4212
0
                  this->GetPolicyStatusCMP0202() == cmPolicies::NEW
4213
0
                    ? this->GetFilePostfix(config)
4214
0
                    : "",
4215
0
                  ".pdb");
4216
0
}
4217
4218
std::string cmGeneratorTarget::GetObjectDirectory(
4219
  std::string const& config) const
4220
0
{
4221
0
  std::string obj_dir =
4222
0
    this->GlobalGenerator->ExpandCFGIntDir(this->ObjectDirectory, config);
4223
#if defined(__APPLE__)
4224
  // Replace Xcode's placeholder for the object file directory since
4225
  // installation and export scripts need to know the real directory.
4226
  // Xcode has build-time settings (e.g. for sanitizers) that affect this,
4227
  // but we use the default here.  Users that want to enable sanitizers
4228
  // will do so at the cost of object library installation and export.
4229
  cmSystemTools::ReplaceString(obj_dir, "$(OBJECT_FILE_DIR_normal:base)",
4230
                               "Objects-normal");
4231
#endif
4232
0
  return obj_dir;
4233
0
}
4234
4235
void cmGeneratorTarget::GetTargetObjectNames(
4236
  std::string const& config, std::vector<std::string>& objects) const
4237
0
{
4238
0
  this->GetTargetObjectNames(
4239
0
    config, [](cmSourceFile const&) -> bool { return true; }, objects);
4240
0
}
4241
4242
void cmGeneratorTarget::GetTargetObjectNames(
4243
  std::string const& config, std::function<bool(cmSourceFile const&)> filter,
4244
  std::vector<std::string>& objects) const
4245
0
{
4246
0
  this->GetTargetObjectLocations(
4247
0
    config, filter,
4248
0
    [&objects](cmObjectLocation const& buildLoc, cmObjectLocation const&) {
4249
0
      objects.push_back(buildLoc.GetPath());
4250
0
    });
4251
0
}
4252
4253
void cmGeneratorTarget::GetTargetObjectLocations(
4254
  std::string const& config,
4255
  std::function<void(cmObjectLocation const&, cmObjectLocation const&)> cb)
4256
  const
4257
0
{
4258
0
  this->GetTargetObjectLocations(
4259
0
    config, [](cmSourceFile const&) -> bool { return true; }, cb);
4260
0
}
4261
4262
void cmGeneratorTarget::GetTargetObjectLocations(
4263
  std::string const& config, std::function<bool(cmSourceFile const&)> filter,
4264
  std::function<void(cmObjectLocation const&, cmObjectLocation const&)> cb)
4265
  const
4266
0
{
4267
0
  std::vector<cmSourceFile const*> objectSources;
4268
0
  this->GetObjectSources(objectSources, config);
4269
0
  std::map<cmSourceFile const*, cmObjectLocations> mapping;
4270
4271
0
  for (cmSourceFile const* sf : objectSources) {
4272
0
    mapping[sf];
4273
0
  }
4274
4275
0
  this->LocalGenerator->ComputeObjectFilenames(mapping, config, this);
4276
4277
0
  auto const buildUseShortPaths = this->GetUseShortObjectNames()
4278
0
    ? cmObjectLocations::UseShortPath::Yes
4279
0
    : cmObjectLocations::UseShortPath::No;
4280
0
  auto const installUseShortPaths = this->GetUseShortObjectNamesForInstall();
4281
4282
0
  for (cmSourceFile const* src : objectSources) {
4283
0
    if (filter(*src)) {
4284
      // Find the object file name corresponding to this source file.
4285
0
      auto map_it = mapping.find(src);
4286
0
      auto const& buildLoc = map_it->second.GetLocation(buildUseShortPaths);
4287
0
      auto const& installLoc =
4288
0
        map_it->second.GetInstallLocation(installUseShortPaths, config);
4289
      // It must exist because we populated the mapping just above.
4290
0
      assert(!buildLoc.GetPath().empty());
4291
0
      assert(!installLoc.GetPath().empty());
4292
0
      cb(buildLoc, installLoc);
4293
0
    }
4294
0
  }
4295
4296
  // We need to compute the relative path from the root of
4297
  // of the object directory to handle subdirectory paths
4298
0
  std::string rootObjectDir = this->GetObjectDirectory(config);
4299
0
  rootObjectDir = cmSystemTools::CollapseFullPath(rootObjectDir);
4300
0
  auto ispcObjects = this->GetGeneratedISPCObjects(config);
4301
0
  for (auto const& output : ispcObjects) {
4302
0
    if (filter(*output.first)) {
4303
0
      auto relativePathFromObjectDir =
4304
0
        output.second.substr(rootObjectDir.size());
4305
0
      cmObjectLocation ispcLoc(relativePathFromObjectDir);
4306
      // FIXME: apply short path to this object if needed.
4307
0
      cb(ispcLoc, ispcLoc);
4308
0
    }
4309
0
  }
4310
0
}
4311
4312
bool cmGeneratorTarget::StrictTargetComparison::operator()(
4313
  cmGeneratorTarget const* t1, cmGeneratorTarget const* t2) const
4314
0
{
4315
0
  int nameResult = strcmp(t1->GetName().c_str(), t2->GetName().c_str());
4316
0
  if (nameResult == 0) {
4317
0
    return strcmp(
4318
0
             t1->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str(),
4319
0
             t2->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str()) < 0;
4320
0
  }
4321
0
  return nameResult < 0;
4322
0
}
4323
4324
struct cmGeneratorTarget::SourceFileFlags
4325
cmGeneratorTarget::GetTargetSourceFileFlags(cmSourceFile const* sf) const
4326
0
{
4327
0
  struct SourceFileFlags flags;
4328
0
  this->ConstructSourceFileFlags();
4329
0
  auto si = this->SourceFlagsMap.find(sf);
4330
0
  if (si != this->SourceFlagsMap.end()) {
4331
0
    flags = si->second;
4332
0
  } else {
4333
    // Handle the MACOSX_PACKAGE_LOCATION property on source files that
4334
    // were not listed in one of the other lists.
4335
0
    if (cmValue location = sf->GetProperty("MACOSX_PACKAGE_LOCATION")) {
4336
0
      flags.MacFolder = location->c_str();
4337
0
      bool const stripResources =
4338
0
        this->GlobalGenerator->ShouldStripResourcePath(this->Makefile);
4339
0
      if (*location == "Resources") {
4340
0
        flags.Type = cmGeneratorTarget::SourceFileTypeResource;
4341
0
        if (stripResources) {
4342
0
          flags.MacFolder = "";
4343
0
        }
4344
0
      } else if (cmHasLiteralPrefix(*location, "Resources/")) {
4345
0
        flags.Type = cmGeneratorTarget::SourceFileTypeDeepResource;
4346
0
        if (stripResources) {
4347
0
          flags.MacFolder += cmStrLen("Resources/");
4348
0
        }
4349
0
      } else {
4350
0
        flags.Type = cmGeneratorTarget::SourceFileTypeMacContent;
4351
0
      }
4352
0
    }
4353
0
  }
4354
0
  return flags;
4355
0
}
4356
4357
void cmGeneratorTarget::ConstructSourceFileFlags() const
4358
0
{
4359
0
  if (this->SourceFileFlagsConstructed) {
4360
0
    return;
4361
0
  }
4362
0
  this->SourceFileFlagsConstructed = true;
4363
4364
  // Process public headers to mark the source files.
4365
0
  if (cmValue files = this->GetProperty("PUBLIC_HEADER")) {
4366
0
    cmList relFiles{ *files };
4367
0
    for (auto const& relFile : relFiles) {
4368
0
      if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
4369
0
        SourceFileFlags& flags = this->SourceFlagsMap[sf];
4370
0
        flags.MacFolder = "Headers";
4371
0
        flags.Type = cmGeneratorTarget::SourceFileTypePublicHeader;
4372
0
      }
4373
0
    }
4374
0
  }
4375
4376
  // Process private headers after public headers so that they take
4377
  // precedence if a file is listed in both.
4378
0
  if (cmValue files = this->GetProperty("PRIVATE_HEADER")) {
4379
0
    cmList relFiles{ *files };
4380
0
    for (auto const& relFile : relFiles) {
4381
0
      if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
4382
0
        SourceFileFlags& flags = this->SourceFlagsMap[sf];
4383
0
        flags.MacFolder = "PrivateHeaders";
4384
0
        flags.Type = cmGeneratorTarget::SourceFileTypePrivateHeader;
4385
0
      }
4386
0
    }
4387
0
  }
4388
4389
  // Mark sources listed as resources.
4390
0
  if (cmValue files = this->GetProperty("RESOURCE")) {
4391
0
    cmList relFiles{ *files };
4392
0
    for (auto const& relFile : relFiles) {
4393
0
      if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
4394
0
        SourceFileFlags& flags = this->SourceFlagsMap[sf];
4395
0
        flags.MacFolder = "";
4396
0
        if (!this->GlobalGenerator->ShouldStripResourcePath(this->Makefile)) {
4397
0
          flags.MacFolder = "Resources";
4398
0
        }
4399
0
        flags.Type = cmGeneratorTarget::SourceFileTypeResource;
4400
0
      }
4401
0
    }
4402
0
  }
4403
0
}
4404
4405
bool cmGeneratorTarget::SetDeviceLink(bool deviceLink)
4406
0
{
4407
0
  bool previous = this->DeviceLink;
4408
0
  this->DeviceLink = deviceLink;
4409
0
  return previous;
4410
0
}
4411
4412
void cmGeneratorTarget::GetTargetVersion(int& major, int& minor) const
4413
0
{
4414
0
  int patch;
4415
0
  this->GetTargetVersion("VERSION", major, minor, patch);
4416
0
}
4417
4418
void cmGeneratorTarget::GetTargetVersionFallback(
4419
  std::string const& property, std::string const& fallback_property,
4420
  int& major, int& minor, int& patch) const
4421
0
{
4422
0
  if (this->GetProperty(property)) {
4423
0
    this->GetTargetVersion(property, major, minor, patch);
4424
0
  } else {
4425
0
    this->GetTargetVersion(fallback_property, major, minor, patch);
4426
0
  }
4427
0
}
4428
4429
void cmGeneratorTarget::GetTargetVersion(std::string const& property,
4430
                                         int& major, int& minor,
4431
                                         int& patch) const
4432
0
{
4433
  // Set the default values.
4434
0
  major = 0;
4435
0
  minor = 0;
4436
0
  patch = 0;
4437
4438
0
  assert(this->GetType() != cm::TargetType::INTERFACE_LIBRARY);
4439
4440
0
  if (cmValue version = this->GetProperty(property)) {
4441
    // Try to parse the version number and store the results that were
4442
    // successfully parsed.
4443
0
    int parsed_major;
4444
0
    int parsed_minor;
4445
0
    int parsed_patch;
4446
0
    switch (sscanf(version->c_str(), "%d.%d.%d", &parsed_major, &parsed_minor,
4447
0
                   &parsed_patch)) {
4448
0
      case 3:
4449
0
        patch = parsed_patch;
4450
0
        CM_FALLTHROUGH;
4451
0
      case 2:
4452
0
        minor = parsed_minor;
4453
0
        CM_FALLTHROUGH;
4454
0
      case 1:
4455
0
        major = parsed_major;
4456
0
        CM_FALLTHROUGH;
4457
0
      default:
4458
0
        break;
4459
0
    }
4460
0
  }
4461
0
}
4462
4463
std::string cmGeneratorTarget::GetRuntimeLinkLibrary(
4464
  std::string const& lang, std::string const& config) const
4465
0
{
4466
  // This is activated by the presence of a default selection whether or
4467
  // not it is overridden by a property.
4468
0
  cmValue runtimeLibraryDefault = this->Makefile->GetDefinition(
4469
0
    cmStrCat("CMAKE_", lang, "_RUNTIME_LIBRARY_DEFAULT"));
4470
0
  if (!cmNonempty(runtimeLibraryDefault)) {
4471
0
    return std::string();
4472
0
  }
4473
0
  cmValue runtimeLibraryValue =
4474
0
    this->Target->GetProperty(cmStrCat(lang, "_RUNTIME_LIBRARY"));
4475
0
  if (!runtimeLibraryValue) {
4476
0
    runtimeLibraryValue = runtimeLibraryDefault;
4477
0
  }
4478
0
  return cmSystemTools::UpperCase(cmGeneratorExpression::Evaluate(
4479
0
    *runtimeLibraryValue, this->LocalGenerator, config, this));
4480
0
}
4481
4482
std::string cmGeneratorTarget::GetFortranModuleDirectory(
4483
  std::string const& working_dir) const
4484
0
{
4485
0
  if (!this->FortranModuleDirectoryCreated) {
4486
0
    this->FortranModuleDirectory =
4487
0
      this->CreateFortranModuleDirectory(working_dir);
4488
0
    this->FortranModuleDirectoryCreated = true;
4489
0
  }
4490
4491
0
  return this->FortranModuleDirectory;
4492
0
}
4493
4494
bool cmGeneratorTarget::IsFortranBuildingIntrinsicModules() const
4495
0
{
4496
  // ATTENTION Before 4.0 the property name was misspelled.
4497
  // Check the correct name first and than the old name.
4498
0
  if (cmValue prop = this->GetProperty("Fortran_BUILDING_INTRINSIC_MODULES")) {
4499
0
    return prop.IsOn();
4500
0
  }
4501
0
  if (cmValue prop =
4502
0
        this->GetProperty("Fortran_BUILDING_INSTRINSIC_MODULES")) {
4503
0
    return prop.IsOn();
4504
0
  }
4505
0
  return false;
4506
0
}
4507
4508
std::string cmGeneratorTarget::CreateFortranModuleDirectory(
4509
  std::string const& working_dir) const
4510
0
{
4511
0
  std::string mod_dir;
4512
0
  std::string target_mod_dir;
4513
0
  if (cmValue prop = this->GetProperty("Fortran_MODULE_DIRECTORY")) {
4514
0
    target_mod_dir = *prop;
4515
0
  } else {
4516
0
    std::string const& default_mod_dir =
4517
0
      this->LocalGenerator->GetCurrentBinaryDirectory();
4518
0
    if (default_mod_dir != working_dir) {
4519
0
      target_mod_dir = default_mod_dir;
4520
0
    }
4521
0
  }
4522
0
  cmValue moddir_flag =
4523
0
    this->Makefile->GetDefinition("CMAKE_Fortran_MODDIR_FLAG");
4524
0
  if (!target_mod_dir.empty() && moddir_flag) {
4525
    // Compute the full path to the module directory.
4526
0
    if (cmSystemTools::FileIsFullPath(target_mod_dir)) {
4527
      // Already a full path.
4528
0
      mod_dir = target_mod_dir;
4529
0
    } else {
4530
      // Interpret relative to the current output directory.
4531
0
      mod_dir = cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(),
4532
0
                         '/', target_mod_dir);
4533
0
    }
4534
4535
    // Make sure the module output directory exists.
4536
0
    cmSystemTools::MakeDirectory(mod_dir);
4537
0
  }
4538
0
  return mod_dir;
4539
0
}
4540
4541
void cmGeneratorTarget::AddISPCGeneratedHeader(std::string const& header,
4542
                                               std::string const& config)
4543
0
{
4544
0
  std::string config_upper;
4545
0
  if (!config.empty()) {
4546
0
    config_upper = cmSystemTools::UpperCase(config);
4547
0
  }
4548
0
  auto iter = this->ISPCGeneratedHeaders.find(config_upper);
4549
0
  if (iter == this->ISPCGeneratedHeaders.end()) {
4550
0
    std::vector<std::string> headers;
4551
0
    headers.emplace_back(header);
4552
0
    this->ISPCGeneratedHeaders.insert({ config_upper, headers });
4553
0
  } else {
4554
0
    iter->second.emplace_back(header);
4555
0
  }
4556
0
}
4557
4558
std::vector<std::string> cmGeneratorTarget::GetGeneratedISPCHeaders(
4559
  std::string const& config) const
4560
0
{
4561
0
  std::string config_upper;
4562
0
  if (!config.empty()) {
4563
0
    config_upper = cmSystemTools::UpperCase(config);
4564
0
  }
4565
0
  auto iter = this->ISPCGeneratedHeaders.find(config_upper);
4566
0
  if (iter == this->ISPCGeneratedHeaders.end()) {
4567
0
    return std::vector<std::string>{};
4568
0
  }
4569
0
  return iter->second;
4570
0
}
4571
4572
void cmGeneratorTarget::AddISPCGeneratedObject(
4573
  std::vector<std::pair<cmSourceFile const*, std::string>>&& objs,
4574
  std::string const& config)
4575
0
{
4576
0
  std::string config_upper;
4577
0
  if (!config.empty()) {
4578
0
    config_upper = cmSystemTools::UpperCase(config);
4579
0
  }
4580
0
  auto iter = this->ISPCGeneratedObjects.find(config_upper);
4581
0
  if (iter == this->ISPCGeneratedObjects.end()) {
4582
0
    this->ISPCGeneratedObjects.insert({ config_upper, objs });
4583
0
  } else {
4584
0
    iter->second.insert(iter->second.end(), objs.begin(), objs.end());
4585
0
  }
4586
0
}
4587
4588
std::vector<std::pair<cmSourceFile const*, std::string>>
4589
cmGeneratorTarget::GetGeneratedISPCObjects(std::string const& config) const
4590
0
{
4591
0
  std::string config_upper;
4592
0
  if (!config.empty()) {
4593
0
    config_upper = cmSystemTools::UpperCase(config);
4594
0
  }
4595
0
  auto iter = this->ISPCGeneratedObjects.find(config_upper);
4596
0
  if (iter == this->ISPCGeneratedObjects.end()) {
4597
0
    return std::vector<std::pair<cmSourceFile const*, std::string>>{};
4598
0
  }
4599
0
  return iter->second;
4600
0
}
4601
4602
std::string cmGeneratorTarget::GetFrameworkVersion() const
4603
0
{
4604
0
  assert(this->GetType() != cm::TargetType::INTERFACE_LIBRARY);
4605
4606
0
  if (cmValue fversion = this->GetProperty("FRAMEWORK_VERSION")) {
4607
0
    return *fversion;
4608
0
  }
4609
0
  if (cmValue tversion = this->GetProperty("VERSION")) {
4610
0
    return *tversion;
4611
0
  }
4612
0
  return "A";
4613
0
}
4614
4615
std::string cmGeneratorTarget::ComputeVersionedName(std::string const& prefix,
4616
                                                    std::string const& base,
4617
                                                    std::string const& suffix,
4618
                                                    std::string const& name,
4619
                                                    cmValue version) const
4620
0
{
4621
0
  std::string vName = this->IsApple() ? (prefix + base) : name;
4622
0
  if (version) {
4623
0
    vName = cmStrCat(std::move(vName), '.', *version);
4624
0
  }
4625
0
  if (this->IsApple()) {
4626
0
    vName += suffix;
4627
0
  }
4628
0
  return vName;
4629
0
}
4630
4631
std::vector<std::string> cmGeneratorTarget::GetPropertyKeys() const
4632
0
{
4633
0
  return this->Target->GetProperties().GetKeys();
4634
0
}
4635
4636
void cmGeneratorTarget::ReportPropertyOrigin(
4637
  std::string const& p, std::string const& result, std::string const& report,
4638
  std::string const& compatibilityType) const
4639
0
{
4640
0
  cmList debugProperties{ this->Target->GetMakefile()->GetDefinition(
4641
0
    "CMAKE_DEBUG_TARGET_PROPERTIES") };
4642
0
  bool debugOrigin = !this->DebugCompatiblePropertiesDone[p] &&
4643
0
    cm::contains(debugProperties, p);
4644
4645
0
  this->DebugCompatiblePropertiesDone[p] = true;
4646
0
  if (!debugOrigin) {
4647
0
    return;
4648
0
  }
4649
4650
0
  std::string areport =
4651
0
    cmStrCat(compatibilityType, " of property \"", p, "\" for target \"",
4652
0
             this->GetName(), "\" (result: \"", result, "\"):\n", report);
4653
4654
0
  this->LocalGenerator->GetCMakeInstance()->IssueMessage(MessageType::LOG,
4655
0
                                                         areport);
4656
0
}
4657
4658
std::string cmGeneratorTarget::GetDirectory(
4659
  std::string const& config, cmStateEnums::ArtifactType artifact) const
4660
0
{
4661
0
  if (this->IsImported()) {
4662
0
    auto fullPath = this->Target->ImportedGetFullPath(config, artifact);
4663
0
    if (this->IsFrameworkOnApple()) {
4664
0
      auto fwDescriptor = this->GetGlobalGenerator()->SplitFrameworkPath(
4665
0
        fullPath, cmGlobalGenerator::FrameworkFormat::Strict);
4666
0
      if (fwDescriptor) {
4667
0
        return fwDescriptor->Directory;
4668
0
      }
4669
0
    }
4670
    // Return the directory from which the target is imported.
4671
0
    return cmSystemTools::GetFilenamePath(fullPath);
4672
0
  }
4673
0
  if (OutputInfo const* info = this->GetOutputInfo(config)) {
4674
    // Return the directory in which the target will be built.
4675
0
    switch (artifact) {
4676
0
      case cmStateEnums::RuntimeBinaryArtifact:
4677
0
        return info->OutDir;
4678
0
      case cmStateEnums::ImportLibraryArtifact:
4679
0
        return info->ImpDir;
4680
0
    }
4681
0
  }
4682
0
  return "";
4683
0
}
4684
4685
bool cmGeneratorTarget::UsesDefaultOutputDir(
4686
  std::string const& config, cmStateEnums::ArtifactType artifact) const
4687
0
{
4688
0
  std::string dir;
4689
0
  return this->ComputeOutputDir(config, artifact, dir);
4690
0
}
4691
4692
cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo(
4693
  std::string const& config) const
4694
0
{
4695
  // There is no output information for imported targets.
4696
0
  if (this->IsImported()) {
4697
0
    return nullptr;
4698
0
  }
4699
4700
  // Synthetic targets don't have output.
4701
0
  if (this->IsSynthetic()) {
4702
0
    return nullptr;
4703
0
  }
4704
4705
  // Only libraries and executables have well-defined output files.
4706
0
  if (!this->HaveWellDefinedOutputFiles()) {
4707
0
    std::string msg = cmStrCat("cmGeneratorTarget::GetOutputInfo called for ",
4708
0
                               this->GetName(), " which has type ",
4709
0
                               cmState::GetTargetTypeName(this->GetType()));
4710
0
    this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
4711
0
    return nullptr;
4712
0
  }
4713
4714
  // Lookup/compute/cache the output information for this configuration.
4715
0
  std::string config_upper;
4716
0
  if (!config.empty()) {
4717
0
    config_upper = cmSystemTools::UpperCase(config);
4718
0
  }
4719
0
  auto i = this->OutputInfoMap.find(config_upper);
4720
0
  if (i == this->OutputInfoMap.end()) {
4721
    // Add empty info in map to detect potential recursion.
4722
0
    OutputInfo info;
4723
0
    OutputInfoMapType::value_type entry(config_upper, info);
4724
0
    i = this->OutputInfoMap.insert(entry).first;
4725
4726
    // Compute output directories.
4727
0
    this->ComputeOutputDir(config, cmStateEnums::RuntimeBinaryArtifact,
4728
0
                           info.OutDir);
4729
0
    this->ComputeOutputDir(config, cmStateEnums::ImportLibraryArtifact,
4730
0
                           info.ImpDir);
4731
0
    if (!this->ComputePDBOutputDir("PDB", config, info.PdbDir)) {
4732
0
      info.PdbDir = info.OutDir;
4733
0
    }
4734
4735
    // Now update the previously-prepared map entry.
4736
0
    i->second = info;
4737
0
  } else if (i->second.empty()) {
4738
    // An empty map entry indicates we have been called recursively
4739
    // from the above block.
4740
0
    this->LocalGenerator->GetCMakeInstance()->IssueMessage(
4741
0
      MessageType::FATAL_ERROR,
4742
0
      cmStrCat("Target '", this->GetName(),
4743
0
               "' OUTPUT_DIRECTORY depends on itself."),
4744
0
      this->GetBacktrace());
4745
0
    return nullptr;
4746
0
  }
4747
0
  return &i->second;
4748
0
}
4749
4750
bool cmGeneratorTarget::ComputeOutputDir(std::string const& config,
4751
                                         cmStateEnums::ArtifactType artifact,
4752
                                         std::string& out) const
4753
0
{
4754
0
  bool usesDefaultOutputDir = false;
4755
0
  std::string conf = config;
4756
4757
  // Look for a target property defining the target output directory
4758
  // based on the target type.
4759
0
  std::string targetTypeName = this->GetOutputTargetType(artifact);
4760
0
  std::string propertyName;
4761
0
  if (!targetTypeName.empty()) {
4762
0
    propertyName = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY");
4763
0
  }
4764
4765
  // Check for a per-configuration output directory target property.
4766
0
  std::string configUpper = cmSystemTools::UpperCase(conf);
4767
0
  std::string configProp;
4768
0
  if (!targetTypeName.empty()) {
4769
0
    configProp = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY_", configUpper);
4770
0
  }
4771
4772
  // Select an output directory.
4773
0
  if (cmValue config_outdir = this->GetProperty(configProp)) {
4774
    // Use the user-specified per-configuration output directory.
4775
0
    out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
4776
0
                                          config, this);
4777
4778
    // Skip per-configuration subdirectory.
4779
0
    conf.clear();
4780
0
  } else if (cmValue outdir = this->GetProperty(propertyName)) {
4781
    // Use the user-specified output directory.
4782
0
    out = cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator,
4783
0
                                          config, this);
4784
    // Skip per-configuration subdirectory if the value contained a
4785
    // generator expression.
4786
0
    if (out != *outdir) {
4787
0
      conf.clear();
4788
0
    }
4789
0
  } else if (this->GetType() == cm::TargetType::EXECUTABLE) {
4790
    // Lookup the output path for executables.
4791
0
    out = this->Makefile->GetSafeDefinition("EXECUTABLE_OUTPUT_PATH");
4792
0
  } else if (this->GetType() == cm::TargetType::STATIC_LIBRARY ||
4793
0
             this->GetType() == cm::TargetType::SHARED_LIBRARY ||
4794
0
             this->GetType() == cm::TargetType::MODULE_LIBRARY) {
4795
    // Lookup the output path for libraries.
4796
0
    out = this->Makefile->GetSafeDefinition("LIBRARY_OUTPUT_PATH");
4797
0
  }
4798
0
  if (out.empty()) {
4799
    // Default to the current output directory.
4800
0
    usesDefaultOutputDir = true;
4801
0
    out = ".";
4802
0
  }
4803
4804
  // Convert the output path to a full path in case it is
4805
  // specified as a relative path.  Treat a relative path as
4806
  // relative to the current output directory for this makefile.
4807
0
  out = (cmSystemTools::CollapseFullPath(
4808
0
    out, this->LocalGenerator->GetCurrentBinaryDirectory()));
4809
4810
  // The generator may add the configuration's subdirectory.
4811
0
  if (!conf.empty()) {
4812
0
    bool useEPN =
4813
0
      this->GlobalGenerator->UseEffectivePlatformName(this->Makefile);
4814
0
    std::string suffix =
4815
0
      usesDefaultOutputDir && useEPN ? "${EFFECTIVE_PLATFORM_NAME}" : "";
4816
0
    this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
4817
0
      "/", conf, suffix, out);
4818
0
  }
4819
4820
0
  return usesDefaultOutputDir;
4821
0
}
4822
4823
bool cmGeneratorTarget::ComputePDBOutputDir(std::string const& kind,
4824
                                            std::string const& config,
4825
                                            std::string& out) const
4826
0
{
4827
  // Look for a target property defining the target output directory
4828
  // based on the target type.
4829
0
  std::string propertyName;
4830
0
  if (!kind.empty()) {
4831
0
    propertyName = cmStrCat(kind, "_OUTPUT_DIRECTORY");
4832
0
  }
4833
0
  std::string conf = config;
4834
4835
  // Check for a per-configuration output directory target property.
4836
0
  std::string configUpper = cmSystemTools::UpperCase(conf);
4837
0
  std::string configProp;
4838
0
  if (!kind.empty()) {
4839
0
    configProp = cmStrCat(kind, "_OUTPUT_DIRECTORY_", configUpper);
4840
0
  }
4841
4842
  // Select an output directory.
4843
0
  if (cmValue config_outdir = this->GetProperty(configProp)) {
4844
    // Use the user-specified per-configuration output directory.
4845
0
    out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
4846
0
                                          config);
4847
4848
    // Skip per-configuration subdirectory.
4849
0
    conf.clear();
4850
0
  } else if (cmValue outdir = this->GetProperty(propertyName)) {
4851
    // Use the user-specified output directory.
4852
0
    out =
4853
0
      cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator, config);
4854
4855
    // Skip per-configuration subdirectory if the value contained a
4856
    // generator expression.
4857
0
    if (out != *outdir) {
4858
0
      conf.clear();
4859
0
    }
4860
0
  }
4861
0
  if (out.empty()) {
4862
0
    cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget();
4863
0
    bool const hasReuse = reuseTarget && reuseTarget != this;
4864
    // Compiler-generated PDB output always needed for REUSE_FROM.
4865
0
    if (kind == "COMPILE_PDB"_s && (this->PchReused || hasReuse)) {
4866
0
      out = this->GetSupportDirectory();
4867
0
    } else {
4868
0
      return false;
4869
0
    }
4870
0
  }
4871
4872
  // Convert the output path to a full path in case it is
4873
  // specified as a relative path.  Treat a relative path as
4874
  // relative to the current output directory for this makefile.
4875
0
  out = (cmSystemTools::CollapseFullPath(
4876
0
    out, this->LocalGenerator->GetCurrentBinaryDirectory()));
4877
4878
  // The generator may add the configuration's subdirectory.
4879
0
  if (!conf.empty()) {
4880
0
    this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
4881
0
      "/", conf, "", out);
4882
0
  }
4883
0
  return true;
4884
0
}
4885
4886
bool cmGeneratorTarget::HaveInstallTreeRPATH(std::string const& config) const
4887
0
{
4888
0
  std::string install_rpath;
4889
0
  this->GetInstallRPATH(config, install_rpath);
4890
0
  return !install_rpath.empty() &&
4891
0
    !this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH");
4892
0
}
4893
4894
bool cmGeneratorTarget::GetBuildRPATH(std::string const& config,
4895
                                      std::string& rpath) const
4896
0
{
4897
0
  return this->GetRPATH(config, "BUILD_RPATH", rpath);
4898
0
}
4899
4900
bool cmGeneratorTarget::GetInstallRPATH(std::string const& config,
4901
                                        std::string& rpath) const
4902
0
{
4903
0
  return this->GetRPATH(config, "INSTALL_RPATH", rpath);
4904
0
}
4905
4906
bool cmGeneratorTarget::GetRPATH(std::string const& config,
4907
                                 std::string const& prop,
4908
                                 std::string& rpath) const
4909
0
{
4910
0
  cmValue value = this->GetProperty(prop);
4911
0
  if (!value) {
4912
0
    return false;
4913
0
  }
4914
4915
0
  rpath =
4916
0
    cmGeneratorExpression::Evaluate(*value, this->LocalGenerator, config);
4917
4918
0
  return true;
4919
0
}
4920
4921
cmGeneratorTarget::ImportInfo const* cmGeneratorTarget::GetImportInfo(
4922
  std::string const& config) const
4923
0
{
4924
  // There is no imported information for non-imported targets.
4925
0
  if (!this->IsImported()) {
4926
0
    return nullptr;
4927
0
  }
4928
4929
  // Lookup/compute/cache the import information for this
4930
  // configuration.
4931
0
  std::string config_upper;
4932
0
  if (!config.empty()) {
4933
0
    config_upper = cmSystemTools::UpperCase(config);
4934
0
  } else {
4935
0
    config_upper = "NOCONFIG";
4936
0
  }
4937
4938
0
  auto i = this->ImportInfoMap.find(config_upper);
4939
0
  if (i == this->ImportInfoMap.end()) {
4940
0
    ImportInfo info;
4941
0
    this->ComputeImportInfo(config_upper, info);
4942
0
    ImportInfoMapType::value_type entry(config_upper, info);
4943
0
    i = this->ImportInfoMap.insert(entry).first;
4944
0
  }
4945
4946
0
  if (this->GetType() == cm::TargetType::INTERFACE_LIBRARY) {
4947
0
    return &i->second;
4948
0
  }
4949
  // If the location is empty then the target is not available for
4950
  // this configuration.
4951
0
  if (i->second.Location.empty() && i->second.ImportLibrary.empty()) {
4952
0
    return nullptr;
4953
0
  }
4954
4955
  // Return the import information.
4956
0
  return &i->second;
4957
0
}
4958
4959
void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
4960
                                          ImportInfo& info) const
4961
0
{
4962
  // This method finds information about an imported target from its
4963
  // properties.  The "IMPORTED_" namespace is reserved for properties
4964
  // defined by the project exporting the target.
4965
4966
  // Initialize members.
4967
0
  info.NoSOName = false;
4968
4969
0
  cmValue loc = nullptr;
4970
0
  cmValue imp = nullptr;
4971
0
  std::string suffix;
4972
0
  if (!this->Target->GetMappedConfig(desired_config, loc, imp, suffix)) {
4973
0
    return;
4974
0
  }
4975
4976
  // Get the link interface.
4977
0
  {
4978
    // Use the INTERFACE_LINK_LIBRARIES special representation directly
4979
    // to get backtraces.
4980
0
    cmBTStringRange entries = this->Target->GetLinkInterfaceEntries();
4981
0
    if (!entries.empty()) {
4982
0
      info.LibrariesProp = "INTERFACE_LINK_LIBRARIES";
4983
0
      for (BT<std::string> const& entry : entries) {
4984
0
        info.Libraries.emplace_back(entry);
4985
0
      }
4986
0
    } else if (this->GetType() != cm::TargetType::INTERFACE_LIBRARY) {
4987
0
      std::string linkProp =
4988
0
        cmStrCat("IMPORTED_LINK_INTERFACE_LIBRARIES", suffix);
4989
0
      cmValue propertyLibs = this->GetProperty(linkProp);
4990
0
      if (!propertyLibs) {
4991
0
        linkProp = "IMPORTED_LINK_INTERFACE_LIBRARIES";
4992
0
        propertyLibs = this->GetProperty(linkProp);
4993
0
      }
4994
0
      if (propertyLibs) {
4995
0
        info.LibrariesProp = linkProp;
4996
0
        info.Libraries.emplace_back(*propertyLibs);
4997
0
      }
4998
0
    }
4999
0
  }
5000
0
  for (BT<std::string> const& entry :
5001
0
       this->Target->GetLinkInterfaceDirectEntries()) {
5002
0
    info.LibrariesHeadInclude.emplace_back(entry);
5003
0
  }
5004
0
  for (BT<std::string> const& entry :
5005
0
       this->Target->GetLinkInterfaceDirectExcludeEntries()) {
5006
0
    info.LibrariesHeadExclude.emplace_back(entry);
5007
0
  }
5008
0
  if (this->GetType() == cm::TargetType::INTERFACE_LIBRARY) {
5009
0
    if (loc) {
5010
0
      info.LibName = *loc;
5011
0
    }
5012
0
    return;
5013
0
  }
5014
5015
  // A provided configuration has been chosen.  Load the
5016
  // configuration's properties.
5017
5018
  // Get the location.
5019
0
  if (loc) {
5020
0
    info.Location = *loc;
5021
0
  } else {
5022
0
    std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
5023
0
    if (cmValue config_location = this->GetProperty(impProp)) {
5024
0
      info.Location = *config_location;
5025
0
    } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
5026
0
      info.Location = *location;
5027
0
    }
5028
0
  }
5029
5030
  // Get the soname.
5031
0
  if (this->GetType() == cm::TargetType::SHARED_LIBRARY) {
5032
0
    std::string soProp = cmStrCat("IMPORTED_SONAME", suffix);
5033
0
    if (cmValue config_soname = this->GetProperty(soProp)) {
5034
0
      info.SOName = *config_soname;
5035
0
    } else if (cmValue soname = this->GetProperty("IMPORTED_SONAME")) {
5036
0
      info.SOName = *soname;
5037
0
    }
5038
0
  }
5039
5040
  // Get the "no-soname" mark.
5041
0
  if (this->GetType() == cm::TargetType::SHARED_LIBRARY) {
5042
0
    std::string soProp = cmStrCat("IMPORTED_NO_SONAME", suffix);
5043
0
    if (cmValue config_no_soname = this->GetProperty(soProp)) {
5044
0
      info.NoSOName = config_no_soname.IsOn();
5045
0
    } else if (cmValue no_soname = this->GetProperty("IMPORTED_NO_SONAME")) {
5046
0
      info.NoSOName = no_soname.IsOn();
5047
0
    }
5048
0
  }
5049
5050
  // Get the import library.
5051
0
  if (imp) {
5052
0
    info.ImportLibrary = *imp;
5053
0
  } else if (this->GetType() == cm::TargetType::SHARED_LIBRARY ||
5054
0
             this->IsExecutableWithExports()) {
5055
0
    std::string impProp = cmStrCat("IMPORTED_IMPLIB", suffix);
5056
0
    if (cmValue config_implib = this->GetProperty(impProp)) {
5057
0
      info.ImportLibrary = *config_implib;
5058
0
    } else if (cmValue implib = this->GetProperty("IMPORTED_IMPLIB")) {
5059
0
      info.ImportLibrary = *implib;
5060
0
    }
5061
0
  }
5062
5063
  // Get the link dependencies.
5064
0
  {
5065
0
    std::string linkProp =
5066
0
      cmStrCat("IMPORTED_LINK_DEPENDENT_LIBRARIES", suffix);
5067
0
    if (cmValue config_libs = this->GetProperty(linkProp)) {
5068
0
      info.SharedDeps = *config_libs;
5069
0
    } else if (cmValue libs =
5070
0
                 this->GetProperty("IMPORTED_LINK_DEPENDENT_LIBRARIES")) {
5071
0
      info.SharedDeps = *libs;
5072
0
    }
5073
0
  }
5074
5075
  // Get the link languages.
5076
0
  if (this->LinkLanguagePropagatesToDependents()) {
5077
0
    std::string linkProp =
5078
0
      cmStrCat("IMPORTED_LINK_INTERFACE_LANGUAGES", suffix);
5079
0
    if (cmValue config_libs = this->GetProperty(linkProp)) {
5080
0
      info.Languages = *config_libs;
5081
0
    } else if (cmValue libs =
5082
0
                 this->GetProperty("IMPORTED_LINK_INTERFACE_LANGUAGES")) {
5083
0
      info.Languages = *libs;
5084
0
    }
5085
0
  }
5086
5087
  // Get information if target is managed assembly.
5088
0
  {
5089
0
    std::string linkProp = "IMPORTED_COMMON_LANGUAGE_RUNTIME";
5090
0
    if (cmValue pc = this->GetProperty(linkProp + suffix)) {
5091
0
      info.Managed = this->CheckManagedType(*pc);
5092
0
    } else if (cmValue p = this->GetProperty(linkProp)) {
5093
0
      info.Managed = this->CheckManagedType(*p);
5094
0
    }
5095
0
  }
5096
5097
  // Get the cyclic repetition count.
5098
0
  if (this->GetType() == cm::TargetType::STATIC_LIBRARY) {
5099
0
    std::string linkProp =
5100
0
      cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix);
5101
0
    if (cmValue config_reps = this->GetProperty(linkProp)) {
5102
0
      sscanf(config_reps->c_str(), "%u", &info.Multiplicity);
5103
0
    } else if (cmValue reps =
5104
0
                 this->GetProperty("IMPORTED_LINK_INTERFACE_MULTIPLICITY")) {
5105
0
      sscanf(reps->c_str(), "%u", &info.Multiplicity);
5106
0
    }
5107
0
  }
5108
0
}
5109
5110
bool cmGeneratorTarget::GetConfigCommonSourceFilesForXcode(
5111
  std::vector<cmSourceFile*>& files) const
5112
0
{
5113
0
  std::vector<std::string> const& configs =
5114
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
5115
5116
0
  auto it = configs.begin();
5117
0
  std::string const& firstConfig = *it;
5118
0
  this->GetSourceFilesWithoutObjectLibraries(files, firstConfig);
5119
5120
0
  for (; it != configs.end(); ++it) {
5121
0
    std::vector<cmSourceFile*> configFiles;
5122
0
    this->GetSourceFilesWithoutObjectLibraries(configFiles, *it);
5123
0
    if (configFiles != files) {
5124
0
      std::string firstConfigFiles;
5125
0
      char const* sep = "";
5126
0
      for (cmSourceFile* f : files) {
5127
0
        firstConfigFiles =
5128
0
          cmStrCat(std::move(firstConfigFiles), sep, f->ResolveFullPath());
5129
0
        sep = "\n  ";
5130
0
      }
5131
5132
0
      std::string thisConfigFiles;
5133
0
      sep = "";
5134
0
      for (cmSourceFile* f : configFiles) {
5135
0
        thisConfigFiles =
5136
0
          cmStrCat(std::move(thisConfigFiles), sep, f->ResolveFullPath());
5137
0
        sep = "\n  ";
5138
0
      }
5139
      /* clang-format off */
5140
0
      std::string e = cmStrCat("Target \"", this->GetName(),
5141
0
        "\" has source files which vary by "
5142
0
        "configuration. This is not supported by the \"",
5143
0
         this->GlobalGenerator->GetName(),
5144
0
         "\" generator.\n"
5145
0
          "Config \"", firstConfig, "\":\n"
5146
0
          "  ", firstConfigFiles, "\n"
5147
0
          "Config \"", *it, "\":\n"
5148
0
          "  ", thisConfigFiles, '\n');
5149
      /* clang-format on */
5150
0
      this->LocalGenerator->IssueMessage(MessageType::FATAL_ERROR, e);
5151
0
      return false;
5152
0
    }
5153
0
  }
5154
0
  return true;
5155
0
}
5156
5157
void cmGeneratorTarget::GetObjectLibrariesInSources(
5158
  std::vector<BT<cmGeneratorTarget*>>& objlibs) const
5159
0
{
5160
  // FIXME: This searches SOURCES for TARGET_OBJECTS for backwards
5161
  // compatibility with the OLD behavior of CMP0026 since this
5162
  // could be called at configure time.  CMP0026 has been removed,
5163
  // so this should now be called only at generate time.
5164
  // Therefore we should be able to improve the implementation
5165
  // with generate-time information.
5166
0
  cmBTStringRange rng = this->Target->GetSourceEntries();
5167
0
  for (auto const& entry : rng) {
5168
0
    cmList files{ entry.Value };
5169
0
    for (auto const& li : files) {
5170
0
      if (cmHasLiteralPrefix(li, "$<TARGET_OBJECTS:") && li.back() == '>') {
5171
0
        std::string objLibName = li.substr(17, li.size() - 18);
5172
5173
0
        if (cmGeneratorExpression::Find(objLibName) != std::string::npos) {
5174
0
          continue;
5175
0
        }
5176
0
        cmGeneratorTarget* objLib =
5177
0
          this->LocalGenerator->FindGeneratorTargetToUse(objLibName);
5178
0
        if (objLib) {
5179
0
          objlibs.emplace_back(objLib, entry.Backtrace);
5180
0
        }
5181
0
      }
5182
0
    }
5183
0
  }
5184
0
}
5185
5186
std::string cmGeneratorTarget::CheckCMP0004(std::string const& item) const
5187
0
{
5188
  // Strip whitespace off the library names because we used to do this
5189
  // in case variables were expanded at generate time.  We no longer
5190
  // do the expansion but users link to libraries like " ${VAR} ".
5191
0
  std::string lib = item;
5192
0
  std::string::size_type pos = lib.find_first_not_of(" \t\r\n");
5193
0
  if (pos != std::string::npos) {
5194
0
    lib = lib.substr(pos);
5195
0
  }
5196
0
  pos = lib.find_last_not_of(" \t\r\n");
5197
0
  if (pos != std::string::npos) {
5198
0
    lib.resize(pos + 1);
5199
0
  }
5200
0
  if (lib != item) {
5201
0
    cmake* cm = this->LocalGenerator->GetCMakeInstance();
5202
0
    std::ostringstream e;
5203
0
    e << "Target \"" << this->GetName() << "\" links to item \"" << item
5204
0
      << "\" which has leading or trailing whitespace.  "
5205
0
      << "This is now an error according to policy CMP0004.";
5206
0
    cm->IssueMessage(MessageType::FATAL_ERROR, e.str(), this->GetBacktrace());
5207
0
  }
5208
0
  return lib;
5209
0
}
5210
5211
bool cmGeneratorTarget::IsDeprecated() const
5212
0
{
5213
0
  cmValue deprecation = this->GetProperty("DEPRECATION");
5214
0
  return cmNonempty(deprecation);
5215
0
}
5216
5217
std::string cmGeneratorTarget::GetDeprecation() const
5218
0
{
5219
  // find DEPRECATION property
5220
0
  if (cmValue deprecation = this->GetProperty("DEPRECATION")) {
5221
0
    return *deprecation;
5222
0
  }
5223
0
  return std::string();
5224
0
}
5225
5226
void cmGeneratorTarget::GetLanguages(std::set<std::string>& languages,
5227
                                     std::string const& config) const
5228
0
{
5229
  // Targets that do not compile anything have no languages.
5230
0
  if (!this->CanCompileSources()) {
5231
0
    return;
5232
0
  }
5233
5234
0
  std::vector<cmSourceFile*> sourceFiles;
5235
0
  this->GetSourceFiles(sourceFiles, config);
5236
0
  for (cmSourceFile* src : sourceFiles) {
5237
0
    std::string const& lang = src->GetOrDetermineLanguage();
5238
0
    if (!lang.empty()) {
5239
0
      languages.insert(lang);
5240
0
    }
5241
0
  }
5242
5243
0
  std::set<cmGeneratorTarget const*> objectLibraries =
5244
0
    this->GetSourceObjectLibraries(config);
5245
0
  for (cmGeneratorTarget const* objLib : objectLibraries) {
5246
0
    objLib->GetLanguages(languages, config);
5247
0
  }
5248
0
}
5249
5250
std::set<cmGeneratorTarget const*> cmGeneratorTarget::GetSourceObjectLibraries(
5251
  std::string const& config) const
5252
0
{
5253
0
  std::set<cmGeneratorTarget const*> objectLibraries;
5254
0
  std::vector<cmSourceFile const*> externalObjects;
5255
0
  this->GetExternalObjects(externalObjects, config);
5256
0
  for (cmSourceFile const* extObj : externalObjects) {
5257
0
    std::string objLib = extObj->GetObjectLibrary();
5258
0
    if (cmGeneratorTarget* tgt =
5259
0
          this->LocalGenerator->FindGeneratorTargetToUse(objLib)) {
5260
0
      objectLibraries.insert(tgt);
5261
0
    }
5262
0
  }
5263
5264
0
  return objectLibraries;
5265
0
}
5266
5267
bool cmGeneratorTarget::IsLanguageUsed(std::string const& language,
5268
                                       std::string const& config) const
5269
0
{
5270
0
  std::set<std::string> languages;
5271
0
  this->GetLanguages(languages, config);
5272
0
  return languages.count(language);
5273
0
}
5274
5275
bool cmGeneratorTarget::IsCSharpOnly() const
5276
0
{
5277
  // Only certain target types may compile CSharp.
5278
0
  if (this->GetType() != cm::TargetType::SHARED_LIBRARY &&
5279
0
      this->GetType() != cm::TargetType::STATIC_LIBRARY &&
5280
0
      this->GetType() != cm::TargetType::EXECUTABLE) {
5281
0
    return false;
5282
0
  }
5283
0
  std::set<std::string> languages = this->GetAllConfigCompileLanguages();
5284
  // Consider an explicit linker language property, but *not* the
5285
  // computed linker language that may depend on linked targets.
5286
0
  cmValue linkLang = this->GetProperty("LINKER_LANGUAGE");
5287
0
  if (cmNonempty(linkLang)) {
5288
0
    languages.insert(*linkLang);
5289
0
  }
5290
0
  return languages.size() == 1 && languages.count("CSharp") > 0;
5291
0
}
5292
5293
bool cmGeneratorTarget::IsDotNetSdkTarget() const
5294
0
{
5295
0
  return !this->GetProperty("DOTNET_SDK").IsEmpty();
5296
0
}
5297
5298
void cmGeneratorTarget::ComputeLinkImplementationLanguages(
5299
  std::string const& config, cmOptionalLinkImplementation& impl) const
5300
0
{
5301
  // This target needs runtime libraries for its source languages.
5302
0
  std::set<std::string> languages;
5303
  // Get languages used in our source files.
5304
0
  this->GetLanguages(languages, config);
5305
  // Copy the set of languages to the link implementation.
5306
0
  impl.Languages.insert(impl.Languages.begin(), languages.begin(),
5307
0
                        languages.end());
5308
0
}
5309
5310
bool cmGeneratorTarget::HaveBuildTreeRPATH(std::string const& config) const
5311
0
{
5312
0
  if (this->GetPropertyAsBool("SKIP_BUILD_RPATH")) {
5313
0
    return false;
5314
0
  }
5315
0
  std::string build_rpath;
5316
0
  if (this->GetBuildRPATH(config, build_rpath)) {
5317
0
    return true;
5318
0
  }
5319
0
  if (cmLinkImplementationLibraries const* impl =
5320
0
        this->GetLinkImplementationLibraries(config, UseTo::Link)) {
5321
0
    return !impl->Libraries.empty();
5322
0
  }
5323
0
  return false;
5324
0
}
5325
5326
bool cmGeneratorTarget::IsNullImpliedByLinkLibraries(
5327
  std::string const& p) const
5328
0
{
5329
0
  return cm::contains(this->LinkImplicitNullProperties, p);
5330
0
}
5331
5332
namespace {
5333
bool CreateCxxStdlibTarget(cmMakefile* makefile, cmLocalGenerator* lg,
5334
                           std::string const& targetName,
5335
                           std::vector<std::string> const& configs)
5336
0
{
5337
0
#ifndef CMAKE_BOOTSTRAP
5338
5339
0
  static cm::optional<cmCxxModuleMetadata> metadata;
5340
5341
  // Load metadata only when we need to create a target
5342
0
  if (!metadata) {
5343
0
    auto errorMessage =
5344
0
      makefile->GetDefinition("CMAKE_CXX_COMPILER_IMPORT_STD_ERROR_MESSAGE");
5345
0
    if (!errorMessage.IsEmpty()) {
5346
0
      makefile->IssueMessage(
5347
0
        MessageType::FATAL_ERROR,
5348
0
        cmStrCat(R"(The "CXX_MODULE_STD" property on target ")", targetName,
5349
0
                 "\" requires toolchain support, but it was not provided.  "
5350
0
                 "Reason:\n  ",
5351
0
                 *errorMessage));
5352
0
      return false;
5353
0
    }
5354
5355
0
    auto metadataPath =
5356
0
      makefile->GetDefinition("CMAKE_CXX_STDLIB_MODULES_JSON");
5357
0
    if (metadataPath.IsEmpty()) {
5358
0
      makefile->IssueMessage(
5359
0
        MessageType::FATAL_ERROR,
5360
0
        cmStrCat(
5361
0
          R"("The "CXX_MODULE_STD" property on target ")", targetName,
5362
0
          "\" requires CMAKE_CXX_STDLIB_MODULES_JSON be set, but it was not "
5363
0
          "provided by the toolchain."));
5364
0
      return false;
5365
0
    }
5366
5367
0
    auto parseResult = cmCxxModuleMetadata::LoadFromFile(*metadataPath);
5368
0
    if (!parseResult) {
5369
0
      makefile->IssueMessage(
5370
0
        MessageType::FATAL_ERROR,
5371
0
        cmStrCat("Failed to load C++ standard library modules metadata "
5372
0
                 "from \"",
5373
0
                 *metadataPath, "\": ", parseResult.Error));
5374
0
      return false;
5375
0
    }
5376
5377
0
    metadata = std::move(*parseResult.Meta);
5378
0
  }
5379
5380
0
  auto* stdlibTgt = makefile->AddLibrary(
5381
0
    "@cmake_cxx_std", cm::TargetType::STATIC_LIBRARY, {}, true);
5382
0
  cmCxxModuleMetadata::PopulateTarget(*stdlibTgt, *metadata, configs);
5383
0
  cmStandardLevelResolver standardResolver(makefile);
5384
0
  standardResolver.AddRequiredTargetFeature(stdlibTgt, "cxx_std_20");
5385
0
  auto gt = cm::make_unique<cmGeneratorTarget>(stdlibTgt, lg);
5386
0
  for (auto const& config : configs) {
5387
0
    gt->ComputeCompileFeatures(config);
5388
0
  }
5389
5390
0
  lg->AddGeneratorTarget(std::move(gt));
5391
5392
0
#endif // CMAKE_BOOTSTRAP
5393
5394
0
  return true;
5395
0
}
5396
} // namespace
5397
5398
bool cmGeneratorTarget::ApplyCXXStdTarget()
5399
0
{
5400
0
  std::vector<std::string> const& configs =
5401
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
5402
0
  auto std_prop = this->GetProperty("CXX_MODULE_STD");
5403
0
  if (!std_prop) {
5404
    // TODO(cxxmodules): Add a target policy to flip the default here. Set
5405
    // `std_prop` based on it.
5406
0
    return true;
5407
0
  }
5408
5409
0
  std::string std_prop_value;
5410
0
  if (std_prop) {
5411
    // Evaluate generator expressions.
5412
0
    cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
5413
0
    auto cge = ge.Parse(*std_prop);
5414
0
    if (!cge) {
5415
0
      this->Makefile->IssueMessage(
5416
0
        MessageType::FATAL_ERROR,
5417
0
        cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
5418
0
                 this->GetName(), "\" is not a valid generator expression."));
5419
0
      return false;
5420
0
    }
5421
    // But do not allow context-sensitive queries. Whether a target uses
5422
    // `import std` should not depend on configuration or properties of the
5423
    // consumer (head target). The link language also shouldn't matter, so ban
5424
    // it as well.
5425
0
    if (cge->GetHadHeadSensitiveCondition()) {
5426
      // Not reachable; all target-sensitive genexes actually fail to parse.
5427
0
      this->Makefile->IssueMessage(
5428
0
        MessageType::FATAL_ERROR,
5429
0
        cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
5430
0
                 this->GetName(),
5431
0
                 "\" contains a condition that queries the "
5432
0
                 "consuming target which is not supported."));
5433
0
      return false;
5434
0
    }
5435
0
    if (cge->GetHadLinkLanguageSensitiveCondition()) {
5436
      // Not reachable; all link language genexes actually fail to parse.
5437
0
      this->Makefile->IssueMessage(
5438
0
        MessageType::FATAL_ERROR,
5439
0
        cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
5440
0
                 this->GetName(),
5441
0
                 "\" contains a condition that queries the "
5442
0
                 "link language which is not supported."));
5443
0
      return false;
5444
0
    }
5445
0
    std_prop_value = cge->Evaluate(this->LocalGenerator, "");
5446
0
    if (cge->GetHadContextSensitiveCondition()) {
5447
0
      this->Makefile->IssueMessage(
5448
0
        MessageType::FATAL_ERROR,
5449
0
        cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
5450
0
                 this->GetName(),
5451
0
                 "\" contains a context-sensitive condition "
5452
0
                 "that is not supported."));
5453
0
      return false;
5454
0
    }
5455
0
  }
5456
0
  auto use_std = cmIsOn(std_prop_value);
5457
5458
  // If we have a value and it is not true, there's nothing to do.
5459
0
  if (std_prop && !use_std) {
5460
0
    return true;
5461
0
  }
5462
5463
  // Create the single, unreferenceable import std target if it doesn't
5464
  // already exist. BMI compatibility handles per-consumer standard level
5465
  // differences by creating synthetic targets as needed.
5466
0
  if (!this->Makefile->FindTargetToUse("@cmake_cxx_std") &&
5467
0
      !CreateCxxStdlibTarget(this->Makefile, this->LocalGenerator,
5468
0
                             this->GetName(), configs)) {
5469
0
    return false;
5470
0
  }
5471
5472
0
  this->Target->AppendProperty("LINK_LIBRARIES",
5473
0
                               "$<BUILD_LOCAL_INTERFACE:@cmake_cxx_std>");
5474
5475
  // Check the experimental feature here. A toolchain may have
5476
  // skipped the check in the toolchain preparation logic.
5477
0
  if (!cmExperimental::HasSupportEnabled(
5478
0
        *this->Makefile, cmExperimental::Feature::CxxImportStd)) {
5479
0
    this->Makefile->IssueMessage(
5480
0
      MessageType::FATAL_ERROR,
5481
0
      "Experimental `import std` support not enabled when detecting "
5482
0
      "toolchain; it must be set before `CXX` is enabled (usually a "
5483
0
      "`project()` call).");
5484
0
    return false;
5485
0
  }
5486
5487
0
  return true;
5488
0
}
5489
5490
cmCxxModuleUsageEffects const& cmGeneratorTarget::GetCxxModuleUsageEffects(
5491
  std::string const& config) const
5492
0
{
5493
5494
0
  auto iter = this->CxxModuleUsageEffects.find(config);
5495
0
  if (iter == this->CxxModuleUsageEffects.end()) {
5496
0
    auto result = this->CxxModuleUsageEffects.emplace(
5497
0
      std::pair<std::string, cmCxxModuleUsageEffects>{
5498
0
        config, cmCxxModuleUsageEffects(this, config) });
5499
0
    return result.first->second;
5500
0
  }
5501
5502
0
  return iter->second;
5503
0
}
5504
5505
cmGeneratorTarget const* cmGeneratorTarget::GetTargetForCxxModules(
5506
  std::string const& config, cmGeneratorTarget const& bmiConsumer) const
5507
0
{
5508
0
  auto const& consumingUsage = bmiConsumer.GetCxxModuleUsageEffects(config);
5509
0
  auto const& owningUsage = this->GetCxxModuleUsageEffects(config);
5510
0
  if (consumingUsage.GetHash() == owningUsage.GetHash()) {
5511
0
    if (this->IsImported()) {
5512
0
      return this->GetCxxSyntheticTarget(config, *this);
5513
0
    }
5514
0
    return this;
5515
0
  }
5516
5517
0
  return this->GetCxxSyntheticTarget(config, bmiConsumer);
5518
0
}
5519
5520
cmGeneratorTarget const* cmGeneratorTarget::GetCxxSyntheticTarget(
5521
  std::string const& config, cmGeneratorTarget const& bmiConsumer) const
5522
0
{
5523
0
  auto const& usageHash =
5524
0
    bmiConsumer.GetCxxModuleUsageEffects(config).GetHash();
5525
0
  auto cached = this->SynthCxxTargets.find(usageHash);
5526
0
  if (cached != this->SynthCxxTargets.end()) {
5527
0
    return cached->second;
5528
0
  }
5529
5530
0
  auto targetNameBase = this->GetName();
5531
0
  if (this->IsImported()) {
5532
0
    cmSystemTools::ReplaceString(targetNameBase, "::", "__");
5533
0
  }
5534
0
  auto const targetName =
5535
0
    cmStrCat(targetNameBase, "@synth_", this->SynthCxxTargets.size());
5536
5537
0
  std::vector<std::string> allConfigs =
5538
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
5539
0
  auto const* model = this->Target;
5540
0
  auto* mf = this->Makefile;
5541
0
  auto* lg = this->GetLocalGenerator();
5542
0
  auto* tgt =
5543
0
    mf->AddSynthesizedTarget(cm::TargetType::INTERFACE_LIBRARY, targetName);
5544
5545
  // Copy relevant information from the existing target.
5546
5547
  // Copy policies to the target.
5548
0
  tgt->CopyPolicyStatuses(model);
5549
5550
  // Copy file sets.
5551
0
  {
5552
0
    for (auto const* gfs :
5553
0
         this->GetInterfaceFileSets(cm::FileSetMetadata::CXX_MODULES)) {
5554
0
      auto* newFs =
5555
0
        tgt
5556
0
          ->GetOrCreateFileSet(gfs->GetName(), gfs->GetType(),
5557
0
                               cm::FileSetMetadata::Visibility::Public)
5558
0
          .first;
5559
0
      newFs->CopyEntries(gfs->GetFileSet());
5560
0
    }
5561
0
  }
5562
5563
  // Copy properties which effect consumer compatibility.
5564
  // CopyUsageEffects now uses the consumer's full (own + transitive)
5565
  // compile features and options.
5566
0
  tgt->CopyUsageEffects(&bmiConsumer, config);
5567
5568
  // Copy properties which don't effect consumer compatibility
5569
0
  tgt->CopyCxxModulesEntries(model);
5570
5571
  // Copy other properties which may affect the C++ module BMI generation.
5572
0
  tgt->CopyCxxModulesProperties(model);
5573
5574
0
  tgt->AddLinkLibrary(*mf, cmStrCat("$<COMPILE_ONLY:", model->GetName(), '>'),
5575
0
                      GENERAL_LibraryType);
5576
5577
  // Create the generator target and attach it to the local generator.
5578
0
  auto gtp = cm::make_unique<cmGeneratorTarget>(tgt, lg);
5579
0
  auto* syntheticTarget = gtp.get();
5580
5581
  // See `localGen->ComputeTargetCompileFeatures()` call in
5582
  // `cmGlobalGenerator::Compute` for where non-synthetic targets resolve
5583
  // this.
5584
0
  for (auto const& innerConfig : allConfigs) {
5585
0
    gtp->ComputeCompileFeatures(innerConfig);
5586
0
  }
5587
  // See `cmGlobalGenerator::ApplyCXXStdTarget` in
5588
  // `cmGlobalGenerator::Compute` for non-synthetic target resolutions.
5589
0
  if (!gtp->ApplyCXXStdTarget()) {
5590
0
    return nullptr;
5591
0
  }
5592
5593
0
  lg->AddGeneratorTarget(std::move(gtp));
5594
0
  this->SynthCxxTargets[usageHash] = syntheticTarget;
5595
0
  if (!syntheticTarget->DiscoverSyntheticTargets(config, &bmiConsumer)) {
5596
0
    return nullptr;
5597
0
  }
5598
5599
0
  return syntheticTarget;
5600
0
}
5601
5602
bool cmGeneratorTarget::DiscoverSyntheticTargets(
5603
  std::string const& config, cmGeneratorTarget const* bmiConsumer)
5604
0
{
5605
0
  auto& configInfo = this->Configs[config];
5606
0
  cmOptionalLinkImplementation impl;
5607
0
  this->ComputeLinkImplementationLibraries(config, impl, UseTo::Link);
5608
5609
0
  if (!bmiConsumer) {
5610
0
    bmiConsumer = this;
5611
0
  }
5612
5613
0
  auto& SyntheticDeps = configInfo.SyntheticDeps;
5614
5615
0
  for (auto const& entry : impl.Libraries) {
5616
0
    auto const* gt = entry.Target;
5617
0
    if (!gt || !gt->HaveInterfaceCxx20ModuleSources()) {
5618
0
      continue;
5619
0
    }
5620
5621
    // Visual Studio generators do not currently support BMI-only compilation,
5622
    // so they can't generate synthetic targets. For consuming native modules,
5623
    // skip so that the native target is used directly. For imported modules,
5624
    // create the synth target anyway and diagnose later, in the VS generator.
5625
0
    if (!gt->IsImported() && this->GlobalGenerator->IsVisualStudio()) {
5626
0
      continue;
5627
0
    }
5628
5629
0
    auto const* dep = gt->GetTargetForCxxModules(config, *bmiConsumer);
5630
0
    if (!dep) {
5631
0
      return false;
5632
0
    }
5633
0
    if (dep->IsSynthetic()) {
5634
0
      SyntheticDeps[gt].push_back(dep);
5635
0
    }
5636
0
  }
5637
5638
0
  return true;
5639
0
}
5640
5641
cmGeneratorTarget::SyntheticDepsMap const& cmGeneratorTarget::GetSyntheticDeps(
5642
  std::string const& config) const
5643
0
{
5644
0
  return this->Configs[config].SyntheticDeps;
5645
0
}
5646
5647
bool cmGeneratorTarget::HasPackageReferences() const
5648
0
{
5649
0
  return this->IsInBuildSystem() &&
5650
0
    !this->GetProperty("VS_PACKAGE_REFERENCES")->empty();
5651
0
}
5652
5653
std::vector<std::string> cmGeneratorTarget::GetPackageReferences() const
5654
0
{
5655
0
  cmList packageReferences;
5656
5657
0
  if (this->IsInBuildSystem()) {
5658
0
    if (cmValue vsPackageReferences =
5659
0
          this->GetProperty("VS_PACKAGE_REFERENCES")) {
5660
0
      packageReferences.assign(*vsPackageReferences);
5661
0
    }
5662
0
  }
5663
5664
0
  return std::move(packageReferences.data());
5665
0
}
5666
5667
std::string cmGeneratorTarget::GetPDBDirectory(std::string const& config) const
5668
0
{
5669
0
  if (OutputInfo const* info = this->GetOutputInfo(config)) {
5670
    // Return the directory in which the target will be built.
5671
0
    return info->PdbDir;
5672
0
  }
5673
0
  return "";
5674
0
}
5675
5676
bool cmGeneratorTarget::HasImplibGNUtoMS(std::string const& config) const
5677
0
{
5678
0
  return this->HasImportLibrary(config) && this->GetPropertyAsBool("GNUtoMS");
5679
0
}
5680
5681
bool cmGeneratorTarget::GetImplibGNUtoMS(std::string const& config,
5682
                                         std::string const& gnuName,
5683
                                         std::string& out,
5684
                                         char const* newExt) const
5685
0
{
5686
0
  if (this->HasImplibGNUtoMS(config) && gnuName.size() > 6 &&
5687
0
      gnuName.substr(gnuName.size() - 6) == ".dll.a") {
5688
0
    out = cmStrCat(cm::string_view(gnuName).substr(0, gnuName.size() - 6),
5689
0
                   newExt ? newExt : ".lib");
5690
0
    return true;
5691
0
  }
5692
0
  return false;
5693
0
}
5694
5695
bool cmGeneratorTarget::HasContextDependentSources() const
5696
0
{
5697
0
  return this->SourcesAreContextDependent == Tribool::True;
5698
0
}
5699
5700
bool cmGeneratorTarget::IsExecutableWithExports() const
5701
0
{
5702
0
  return this->Target->IsExecutableWithExports();
5703
0
}
5704
5705
bool cmGeneratorTarget::IsSharedLibraryWithExports() const
5706
0
{
5707
0
  return this->Target->IsSharedLibraryWithExports();
5708
0
}
5709
5710
bool cmGeneratorTarget::HasImportLibrary(std::string const& config) const
5711
0
{
5712
0
  bool generate_Stubs = true;
5713
0
  if (this->GetGlobalGenerator()->IsXcode()) {
5714
    // take care of CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS variable
5715
    // as well as XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS property
5716
0
    if (cmValue propGenStubs =
5717
0
          this->GetProperty("XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
5718
0
      generate_Stubs = propGenStubs == "YES";
5719
0
    } else if (cmValue varGenStubs = this->Makefile->GetDefinition(
5720
0
                 "CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
5721
0
      generate_Stubs = varGenStubs == "YES";
5722
0
    }
5723
0
  }
5724
5725
0
  return (this->IsDLLPlatform() &&
5726
0
          (this->GetType() == cm::TargetType::SHARED_LIBRARY ||
5727
0
           this->IsExecutableWithExports()) &&
5728
          // Assemblies which have only managed code do not have
5729
          // import libraries.
5730
0
          this->GetManagedType(config) != ManagedType::Managed) ||
5731
0
    (this->IsAIX() && this->IsExecutableWithExports()) ||
5732
0
    (this->Makefile->PlatformSupportsAppleTextStubs() &&
5733
0
     this->IsSharedLibraryWithExports() && generate_Stubs);
5734
0
}
5735
5736
bool cmGeneratorTarget::NeedImportLibraryName(std::string const& config) const
5737
0
{
5738
0
  return this->HasImportLibrary(config) ||
5739
    // On DLL platforms we always generate the import library name
5740
    // just in case the sources have export markup.
5741
0
    (this->IsDLLPlatform() &&
5742
0
     (this->GetType() == cm::TargetType::EXECUTABLE ||
5743
0
      this->GetType() == cm::TargetType::MODULE_LIBRARY));
5744
0
}
5745
5746
bool cmGeneratorTarget::GetUseShortObjectNames(
5747
  cmStateEnums::IntermediateDirKind kind) const
5748
0
{
5749
0
  return this->LocalGenerator->UseShortObjectNames(kind);
5750
0
}
5751
5752
cmObjectLocations::UseShortPath
5753
cmGeneratorTarget::GetUseShortObjectNamesForInstall() const
5754
0
{
5755
0
  auto prop = this->Target->GetProperty("INSTALL_OBJECT_NAME_STRATEGY");
5756
0
  if (prop == "SHORT"_s) {
5757
0
    return cmObjectLocations::UseShortPath::Yes;
5758
0
  }
5759
0
  if (prop == "FULL"_s) {
5760
0
    return cmObjectLocations::UseShortPath::No;
5761
0
  }
5762
0
  if (prop.IsSet()) {
5763
0
    this->Makefile->IssueMessage(
5764
0
      MessageType::FATAL_ERROR,
5765
0
      cmStrCat("Property INSTALL_OBJECT_NAME_STRATEGY of target \"",
5766
0
               this->GetName(), "\" set to the unsupported strategy ", prop));
5767
0
  }
5768
0
  return cmObjectLocations::UseShortPath::No;
5769
0
}
5770
5771
std::string cmGeneratorTarget::GetSupportDirectory(
5772
  cmStateEnums::IntermediateDirKind kind) const
5773
0
{
5774
0
  cmLocalGenerator* lg = this->GetLocalGenerator();
5775
0
  auto targetDir = cmStrCat(lg->GetObjectOutputRoot(kind), '/',
5776
0
                            lg->GetTargetDirectory(this, kind));
5777
5778
0
#ifndef CMAKE_BOOTSTRAP
5779
0
  auto& tdr =
5780
0
    this->GetGlobalGenerator()->RegisterTargetDirectory(this, targetDir);
5781
0
  if (tdr.CollidesWith && !tdr.Warned) {
5782
0
    this->Makefile->IssueMessage(
5783
0
      MessageType::WARNING,
5784
0
      cmStrCat("The '", tdr.CollidesWith->GetName(), "' and '",
5785
0
               this->GetName(),
5786
0
               "' targets share an intermediate directory\n    ", targetDir,
5787
0
               "\nwhich may cause problems with the build graph. This project "
5788
0
               "is not compatible with the `SHORT` target intermediate "
5789
0
               "directory strategy. Possible remedies include: moving the "
5790
0
               "target into different directories or renaming a target."));
5791
0
    tdr.Warned = true;
5792
0
  }
5793
0
#endif
5794
5795
0
  return targetDir;
5796
0
}
5797
5798
std::string cmGeneratorTarget::GetCMFSupportDirectory(
5799
  cmStateEnums::IntermediateDirKind kind) const
5800
0
{
5801
0
  cmLocalGenerator* lg = this->GetLocalGenerator();
5802
0
  if (!lg->AlwaysUsesCMFPaths()) {
5803
0
    return cmStrCat(lg->GetCurrentBinaryDirectory(), "/CMakeFiles/",
5804
0
                    lg->GetTargetDirectory(this, kind));
5805
0
  }
5806
0
  return cmStrCat(lg->GetObjectOutputRoot(kind), '/',
5807
0
                  lg->GetTargetDirectory(this, kind));
5808
0
}
5809
5810
bool cmGeneratorTarget::IsLinkable() const
5811
0
{
5812
0
  return (this->GetType() == cm::TargetType::STATIC_LIBRARY ||
5813
0
          this->GetType() == cm::TargetType::SHARED_LIBRARY ||
5814
0
          this->GetType() == cm::TargetType::MODULE_LIBRARY ||
5815
0
          this->GetType() == cm::TargetType::UNKNOWN_LIBRARY ||
5816
0
          this->GetType() == cm::TargetType::OBJECT_LIBRARY ||
5817
0
          this->GetType() == cm::TargetType::INTERFACE_LIBRARY ||
5818
0
          this->IsExecutableWithExports());
5819
0
}
5820
5821
bool cmGeneratorTarget::HasLinkDependencyFile(std::string const& config) const
5822
0
{
5823
0
  if (this->GetType() != cm::TargetType::EXECUTABLE &&
5824
0
      this->GetType() != cm::TargetType::SHARED_LIBRARY &&
5825
0
      this->GetType() != cm::TargetType::MODULE_LIBRARY) {
5826
0
    return false;
5827
0
  }
5828
5829
0
  if (this->Target->GetProperty("LINK_DEPENDS_NO_SHARED").IsOn()) {
5830
    // Do not use the linker dependency file because it includes shared
5831
    // libraries as well
5832
0
    return false;
5833
0
  }
5834
5835
0
  std::string const depsUseLinker{ "CMAKE_LINK_DEPENDS_USE_LINKER" };
5836
0
  auto linkLanguage = this->GetLinkerLanguage(config);
5837
0
  std::string const langDepsUseLinker{ cmStrCat("CMAKE_", linkLanguage,
5838
0
                                                "_LINK_DEPENDS_USE_LINKER") };
5839
5840
0
  return (!this->Makefile->IsDefinitionSet(depsUseLinker) ||
5841
0
          this->Makefile->IsOn(depsUseLinker)) &&
5842
0
    this->Makefile->IsOn(langDepsUseLinker);
5843
0
}
5844
5845
bool cmGeneratorTarget::IsFrameworkOnApple() const
5846
0
{
5847
0
  return this->Target->IsFrameworkOnApple();
5848
0
}
5849
5850
bool cmGeneratorTarget::IsArchivedAIXSharedLibrary() const
5851
0
{
5852
0
  return this->Target->IsArchivedAIXSharedLibrary();
5853
0
}
5854
5855
bool cmGeneratorTarget::IsImportedFrameworkFolderOnApple(
5856
  std::string const& config) const
5857
0
{
5858
0
  if (this->IsApple() && this->IsImported() &&
5859
0
      (this->GetType() == cm::TargetType::STATIC_LIBRARY ||
5860
0
       this->GetType() == cm::TargetType::SHARED_LIBRARY ||
5861
0
       this->GetType() == cm::TargetType::UNKNOWN_LIBRARY)) {
5862
0
    std::string cfg = config;
5863
0
    if (cfg.empty() && this->GetGlobalGenerator()->IsXcode()) {
5864
      // FIXME(#25515): Remove the need for this workaround.
5865
      // The Xcode generator queries include directories without any
5866
      // specific configuration.  Pick one in case this target does
5867
      // not set either IMPORTED_LOCATION or IMPORTED_CONFIGURATIONS.
5868
0
      cfg =
5869
0
        this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)[0];
5870
0
    }
5871
0
    return cmSystemTools::IsPathToFramework(this->GetLocation(cfg));
5872
0
  }
5873
5874
0
  return false;
5875
0
}
5876
5877
bool cmGeneratorTarget::IsAppBundleOnApple() const
5878
0
{
5879
0
  return this->Target->IsAppBundleOnApple();
5880
0
}
5881
5882
bool cmGeneratorTarget::IsXCTestOnApple() const
5883
0
{
5884
0
  return (this->IsCFBundleOnApple() && this->GetPropertyAsBool("XCTEST"));
5885
0
}
5886
5887
bool cmGeneratorTarget::IsCFBundleOnApple() const
5888
0
{
5889
0
  return (this->GetType() == cm::TargetType::MODULE_LIBRARY &&
5890
0
          this->IsApple() && this->GetPropertyAsBool("BUNDLE"));
5891
0
}
5892
5893
cmGeneratorTarget::ManagedType cmGeneratorTarget::CheckManagedType(
5894
  std::string const& propval) const
5895
0
{
5896
  // The type of the managed assembly (mixed unmanaged C++ and C++/CLI,
5897
  // or only C++/CLI) does only depend on whether the property is an empty
5898
  // string or contains any value at all. In Visual Studio generators
5899
  // this propval is prepended with /clr[:] which results in:
5900
  //
5901
  // 1. propval does not exist: no /clr flag, unmanaged target, has import
5902
  //                            lib
5903
  // 2. empty propval:          add /clr as flag, mixed unmanaged/managed
5904
  //                            target, has import lib
5905
  // 3. netcore propval:        add /clr:netcore as flag, mixed
5906
  //                            unmanaged/managed target, has import lib.
5907
  // 4. any value (safe,pure):  add /clr:[propval] as flag, target with
5908
  //                            managed code only, no import lib
5909
0
  if (propval.empty() || propval == "netcore") {
5910
0
    return ManagedType::Mixed;
5911
0
  }
5912
0
  return ManagedType::Managed;
5913
0
}
5914
5915
cmGeneratorTarget::ManagedType cmGeneratorTarget::GetManagedType(
5916
  std::string const& config) const
5917
0
{
5918
  // Only libraries and executables can be managed targets.
5919
0
  if (this->GetType() > cm::TargetType::SHARED_LIBRARY) {
5920
0
    return ManagedType::Undefined;
5921
0
  }
5922
5923
0
  if (this->GetType() == cm::TargetType::STATIC_LIBRARY) {
5924
0
    return ManagedType::Native;
5925
0
  }
5926
5927
  // Check imported target.
5928
0
  if (this->IsImported()) {
5929
0
    if (cmGeneratorTarget::ImportInfo const* info =
5930
0
          this->GetImportInfo(config)) {
5931
0
      return info->Managed;
5932
0
    }
5933
0
    return ManagedType::Undefined;
5934
0
  }
5935
5936
  // Check for explicitly set clr target property.
5937
0
  if (cmValue clr = this->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
5938
0
    return this->CheckManagedType(*clr);
5939
0
  }
5940
5941
  // C# targets are always managed. This language specific check
5942
  // is added to avoid that the COMMON_LANGUAGE_RUNTIME target property
5943
  // has to be set manually for C# targets.
5944
0
  return this->IsCSharpOnly() ? ManagedType::Managed : ManagedType::Native;
5945
0
}
5946
5947
std::string cmGeneratorTarget::GetImportedXcFrameworkPath(
5948
  std::string const& config) const
5949
0
{
5950
0
  if (!(this->IsApple() && this->IsImported() &&
5951
0
        (this->GetType() == cm::TargetType::SHARED_LIBRARY ||
5952
0
         this->GetType() == cm::TargetType::STATIC_LIBRARY ||
5953
0
         this->GetType() == cm::TargetType::UNKNOWN_LIBRARY))) {
5954
0
    return {};
5955
0
  }
5956
5957
0
  std::string desiredConfig = config;
5958
0
  if (config.empty()) {
5959
0
    desiredConfig = "NOCONFIG";
5960
0
  }
5961
5962
0
  std::string result;
5963
5964
0
  cmValue loc = nullptr;
5965
0
  cmValue imp = nullptr;
5966
0
  std::string suffix;
5967
5968
0
  if (this->Target->GetMappedConfig(desiredConfig, loc, imp, suffix)) {
5969
0
    if (loc) {
5970
0
      result = *loc;
5971
0
    } else {
5972
0
      std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
5973
0
      if (cmValue configLocation = this->GetProperty(impProp)) {
5974
0
        result = *configLocation;
5975
0
      } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
5976
0
        result = *location;
5977
0
      }
5978
0
    }
5979
5980
0
    if (cmSystemTools::IsPathToXcFramework(result)) {
5981
0
      return result;
5982
0
    }
5983
0
  }
5984
5985
0
  return {};
5986
0
}
5987
5988
bool cmGeneratorTarget::HaveFortranSources(std::string const& config) const
5989
0
{
5990
0
  auto sources = this->GetSourceFiles(config);
5991
0
  bool const have_direct = std::any_of(
5992
0
    sources.begin(), sources.end(), [](BT<cmSourceFile*> const& sf) -> bool {
5993
0
      return sf.Value->GetLanguage() == "Fortran"_s;
5994
0
    });
5995
0
  bool have_via_target_objects = false;
5996
0
  if (!have_direct) {
5997
0
    auto const sourceObjectLibraries = this->GetSourceObjectLibraries(config);
5998
0
    have_via_target_objects =
5999
0
      std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
6000
0
                  [&config](cmGeneratorTarget const* tgt) -> bool {
6001
0
                    return tgt->HaveFortranSources(config);
6002
0
                  });
6003
0
  }
6004
0
  return have_direct || have_via_target_objects;
6005
0
}
6006
6007
bool cmGeneratorTarget::HaveFortranSources() const
6008
0
{
6009
0
  auto sources = this->GetAllConfigSources();
6010
0
  bool const have_direct = std::any_of(
6011
0
    sources.begin(), sources.end(), [](AllConfigSource const& sf) -> bool {
6012
0
      return sf.Source->GetLanguage() == "Fortran"_s;
6013
0
    });
6014
0
  bool have_via_target_objects = false;
6015
0
  if (!have_direct) {
6016
0
    std::vector<std::string> configs =
6017
0
      this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
6018
0
    for (auto const& config : configs) {
6019
0
      auto const sourceObjectLibraries =
6020
0
        this->GetSourceObjectLibraries(config);
6021
0
      have_via_target_objects =
6022
0
        std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
6023
0
                    [&config](cmGeneratorTarget const* tgt) -> bool {
6024
0
                      return tgt->HaveFortranSources(config);
6025
0
                    });
6026
0
      if (have_via_target_objects) {
6027
0
        break;
6028
0
      }
6029
0
    }
6030
0
  }
6031
0
  return have_direct || have_via_target_objects;
6032
0
}
6033
6034
bool cmGeneratorTarget::HaveInterfaceCxx20ModuleSources() const
6035
0
{
6036
0
  return !this->GetInterfaceFileSets(cm::FileSetMetadata::CXX_MODULES).empty();
6037
0
}
6038
bool cmGeneratorTarget::HaveCxx20ModuleSources() const
6039
0
{
6040
0
  return !this->GetFileSets(cm::FileSetMetadata::CXX_MODULES).empty() ||
6041
0
    !this->GetInterfaceFileSets(cm::FileSetMetadata::CXX_MODULES).empty();
6042
0
}
6043
6044
cmGeneratorTarget::Cxx20SupportLevel cmGeneratorTarget::HaveCxxModuleSupport(
6045
  std::string const& config) const
6046
0
{
6047
0
  auto const* state = this->Makefile->GetState();
6048
0
  if (!state->GetLanguageEnabled("CXX")) {
6049
0
    return Cxx20SupportLevel::MissingCxx;
6050
0
  }
6051
6052
0
  cmValue standardDefault =
6053
0
    this->Makefile->GetDefinition("CMAKE_CXX_STANDARD_DEFAULT");
6054
0
  if (!standardDefault || standardDefault->empty()) {
6055
    // We do not know any meaningful C++ standard levels for this compiler.
6056
0
    return Cxx20SupportLevel::NoCxx20;
6057
0
  }
6058
6059
0
  cmStandardLevelResolver standardResolver(this->Makefile);
6060
0
  cmStandardLevel const cxxStd20 =
6061
0
    *standardResolver.LanguageStandardLevel("CXX", "20");
6062
0
  cm::optional<cmStandardLevel> explicitLevel =
6063
0
    this->GetExplicitStandardLevel("CXX", config);
6064
0
  if (!explicitLevel || *explicitLevel < cxxStd20) {
6065
0
    return Cxx20SupportLevel::NoCxx20;
6066
0
  }
6067
6068
0
  cmValue scandepRule =
6069
0
    this->Makefile->GetDefinition("CMAKE_CXX_SCANDEP_SOURCE");
6070
0
  if (!scandepRule) {
6071
0
    return Cxx20SupportLevel::MissingRule;
6072
0
  }
6073
0
  return Cxx20SupportLevel::Supported;
6074
0
}
6075
6076
void cmGeneratorTarget::CheckCxxModuleStatus(std::string const& config) const
6077
0
{
6078
0
  bool haveScannableSources = false;
6079
6080
  // Check for `CXX_MODULE*` file sets and a lack of support.
6081
0
  if (this->HaveCxx20ModuleSources()) {
6082
0
    haveScannableSources = true;
6083
0
  }
6084
6085
0
  if (!haveScannableSources) {
6086
    // Check to see if there are regular sources that have requested scanning.
6087
0
    auto sources = this->GetSourceFiles(config);
6088
0
    for (auto const& source : sources) {
6089
0
      auto const* sf = source.Value;
6090
0
      auto const& lang = sf->GetLanguage();
6091
0
      if (lang != "CXX"_s) {
6092
0
        continue;
6093
0
      }
6094
      // Ignore sources which do not need dyndep.
6095
0
      if (this->NeedDyndepForSource(lang, config, sf)) {
6096
0
        haveScannableSources = true;
6097
0
      }
6098
0
    }
6099
0
  }
6100
6101
  // If there isn't anything scannable, ignore it.
6102
0
  if (!haveScannableSources) {
6103
0
    return;
6104
0
  }
6105
6106
  // If the generator doesn't support modules at all, error that we have
6107
  // sources that require the support.
6108
0
  if (!this->GetGlobalGenerator()->CheckCxxModuleSupport(
6109
0
        cmGlobalGenerator::CxxModuleSupportQuery::Expected)) {
6110
0
    this->Makefile->IssueMessage(
6111
0
      MessageType::FATAL_ERROR,
6112
0
      cmStrCat("The target named \"", this->GetName(),
6113
0
               "\" has C++ sources that may use modules, but modules are not "
6114
0
               "supported by this generator:\n  ",
6115
0
               this->GetGlobalGenerator()->GetName(),
6116
0
               "\n"
6117
0
               "Modules are supported only by Ninja, Ninja Multi-Config, "
6118
0
               "and Visual Studio generators for VS 17.4 and newer.  "
6119
0
               "See the cmake-cxxmodules(7) manual for details.  "
6120
0
               "Use the CMAKE_CXX_SCAN_FOR_MODULES variable to enable or "
6121
0
               "disable scanning."));
6122
0
    return;
6123
0
  }
6124
6125
0
  switch (this->HaveCxxModuleSupport(config)) {
6126
0
    case cmGeneratorTarget::Cxx20SupportLevel::MissingCxx:
6127
0
      this->Makefile->IssueMessage(
6128
0
        MessageType::FATAL_ERROR,
6129
0
        cmStrCat("The target named \"", this->GetName(),
6130
0
                 "\" has C++ sources that use modules, but the \"CXX\" "
6131
0
                 "language has not been enabled."));
6132
0
      break;
6133
0
    case cmGeneratorTarget::Cxx20SupportLevel::NoCxx20: {
6134
0
      cmStandardLevelResolver standardResolver(this->Makefile);
6135
0
      auto effStandard =
6136
0
        standardResolver.GetEffectiveStandard(this, "CXX", config);
6137
0
      if (effStandard.empty()) {
6138
0
        effStandard = "; no C++ standard found";
6139
0
      } else {
6140
0
        effStandard = cmStrCat("; found \"cxx_std_", effStandard, '"');
6141
0
      }
6142
0
      this->Makefile->IssueMessage(
6143
0
        MessageType::FATAL_ERROR,
6144
0
        cmStrCat(
6145
0
          "The target named \"", this->GetName(),
6146
0
          "\" has C++ sources that use modules, but does not include "
6147
0
          "\"cxx_std_20\" (or newer) among its `target_compile_features`",
6148
0
          effStandard, '.'));
6149
0
    } break;
6150
0
    case cmGeneratorTarget::Cxx20SupportLevel::MissingRule: {
6151
0
      this->Makefile->IssueMessage(
6152
0
        MessageType::FATAL_ERROR,
6153
0
        cmStrCat("The target named \"", this->GetName(),
6154
0
                 "\" has C++ sources that may use modules, but the compiler "
6155
0
                 "does not provide a way to discover the import graph "
6156
0
                 "dependencies.  See the cmake-cxxmodules(7) manual for "
6157
0
                 "details.  Use the CMAKE_CXX_SCAN_FOR_MODULES variable to "
6158
0
                 "enable or disable scanning."));
6159
0
    } break;
6160
0
    case cmGeneratorTarget::Cxx20SupportLevel::Supported:
6161
      // All is well.
6162
0
      break;
6163
0
  }
6164
0
}
6165
6166
bool cmGeneratorTarget::NeedCxxModuleSupport(std::string const& lang,
6167
                                             std::string const& config) const
6168
0
{
6169
0
  if (lang != "CXX"_s) {
6170
0
    return false;
6171
0
  }
6172
0
  return this->HaveCxxModuleSupport(config) == Cxx20SupportLevel::Supported &&
6173
0
    this->GetGlobalGenerator()->CheckCxxModuleSupport(
6174
0
      cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
6175
0
}
6176
6177
bool cmGeneratorTarget::NeedDyndep(std::string const& lang,
6178
                                   std::string const& config) const
6179
0
{
6180
0
  return lang == "Fortran"_s || this->NeedCxxModuleSupport(lang, config);
6181
0
}
6182
6183
bool cmGeneratorTarget::NeedDyndepForSource(std::string const& lang,
6184
                                            std::string const& config,
6185
                                            cmSourceFile const* sf) const
6186
0
{
6187
  // Fortran always needs to be scanned.
6188
0
  if (lang == "Fortran"_s) {
6189
0
    return true;
6190
0
  }
6191
  // Only C++ code needs scanned otherwise.
6192
0
  if (lang != "CXX"_s) {
6193
0
    return false;
6194
0
  }
6195
6196
  // Any file in `CXX_MODULES` file sets need scanned (it being `CXX` is
6197
  // enforced elsewhere).
6198
0
  auto const* fs = this->GetFileSetForSource(config, sf);
6199
0
  if (fs && fs->GetType() == cm::FileSetMetadata::CXX_MODULES) {
6200
0
    return true;
6201
0
  }
6202
6203
0
  auto targetDyndep = this->NeedCxxDyndep(config);
6204
0
  if (targetDyndep == CxxModuleSupport::Unavailable) {
6205
0
    return false;
6206
0
  }
6207
0
  if (fs) {
6208
0
    auto const fsProp = fs->GetProperty("CXX_SCAN_FOR_MODULES");
6209
0
    if (fsProp.IsSet()) {
6210
0
      return fsProp.IsOn();
6211
0
    }
6212
0
  }
6213
0
  auto const sfProp = sf->GetProperty("CXX_SCAN_FOR_MODULES");
6214
0
  if (sfProp.IsSet()) {
6215
0
    return sfProp.IsOn();
6216
0
  }
6217
0
  return targetDyndep == CxxModuleSupport::Enabled;
6218
0
}
6219
6220
cmGeneratorTarget::CxxModuleSupport cmGeneratorTarget::NeedCxxDyndep(
6221
  std::string const& config) const
6222
0
{
6223
0
  bool haveRule = false;
6224
0
  switch (this->HaveCxxModuleSupport(config)) {
6225
0
    case Cxx20SupportLevel::MissingCxx:
6226
0
    case Cxx20SupportLevel::NoCxx20:
6227
0
      return CxxModuleSupport::Unavailable;
6228
0
    case Cxx20SupportLevel::MissingRule:
6229
0
      break;
6230
0
    case Cxx20SupportLevel::Supported:
6231
0
      haveRule = true;
6232
0
      break;
6233
0
  }
6234
0
  bool haveGeneratorSupport =
6235
0
    this->GetGlobalGenerator()->CheckCxxModuleSupport(
6236
0
      cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
6237
0
  auto const tgtProp = this->GetProperty("CXX_SCAN_FOR_MODULES");
6238
0
  if (tgtProp.IsSet()) {
6239
0
    return tgtProp.IsOn() ? CxxModuleSupport::Enabled
6240
0
                          : CxxModuleSupport::Disabled;
6241
0
  }
6242
6243
0
  CxxModuleSupport policyAnswer = CxxModuleSupport::Unavailable;
6244
0
  switch (this->GetPolicyStatusCMP0155()) {
6245
0
    case cmPolicies::WARN:
6246
0
    case cmPolicies::OLD:
6247
      // The OLD behavior is to not scan the source.
6248
0
      policyAnswer = CxxModuleSupport::Disabled;
6249
0
      break;
6250
0
    case cmPolicies::NEW:
6251
      // The NEW behavior is to scan the source if the compiler supports
6252
      // scanning and the generator supports it.
6253
0
      if (haveRule && haveGeneratorSupport) {
6254
0
        policyAnswer = CxxModuleSupport::Enabled;
6255
0
      } else {
6256
0
        policyAnswer = CxxModuleSupport::Disabled;
6257
0
      }
6258
0
      break;
6259
0
  }
6260
0
  return policyAnswer;
6261
0
}
6262
6263
bool cmGeneratorTarget::HasFileSets() const
6264
0
{
6265
0
  return !this->FileSets->Empty();
6266
0
}
6267
6268
std::vector<cmGeneratorFileSet const*> const&
6269
cmGeneratorTarget::GetAllFileSets() const
6270
0
{
6271
0
  return this->FileSets->GetAllFileSets();
6272
0
}
6273
6274
std::vector<cmGeneratorFileSet const*> const& cmGeneratorTarget::GetFileSets(
6275
  cm::string_view type) const
6276
0
{
6277
0
  return this->FileSets->GetFileSets(type);
6278
0
}
6279
std::vector<cmGeneratorFileSet const*> const&
6280
cmGeneratorTarget::GetInterfaceFileSets(cm::string_view type) const
6281
0
{
6282
0
  return this->FileSets->GetInterfaceFileSets(type);
6283
0
}
6284
6285
cmGeneratorFileSet const* cmGeneratorTarget::GetFileSet(
6286
  std::string const& name) const
6287
0
{
6288
0
  return this->FileSets->GetFileSet(name);
6289
0
}
6290
6291
cmGeneratorFileSet const* cmGeneratorTarget::GetFileSetForSource(
6292
  std::string const& config, cmSourceFile const* sf) const
6293
0
{
6294
0
  return this->FileSets->GetFileSetForSource(config, sf);
6295
0
}
6296
6297
std::string cmGeneratorTarget::BuildDatabasePath(
6298
  std::string const& lang, std::string const& config) const
6299
0
{
6300
  // Check to see if the target wants it.
6301
0
  if (!this->GetPropertyAsBool("EXPORT_BUILD_DATABASE")) {
6302
0
    return {};
6303
0
  }
6304
0
  if (!cmExperimental::HasSupportEnabled(
6305
0
        *this->Makefile, cmExperimental::Feature::ExportBuildDatabase)) {
6306
0
    return {};
6307
0
  }
6308
  // Check to see if the generator supports it.
6309
0
  if (!this->GetGlobalGenerator()->SupportsBuildDatabase()) {
6310
0
    return {};
6311
0
  }
6312
6313
0
  if (this->GetGlobalGenerator()->IsMultiConfig()) {
6314
0
    return cmStrCat(this->GetSupportDirectory(), '/', config, '/', lang,
6315
0
                    "_build_database.json");
6316
0
  }
6317
6318
0
  return cmStrCat(this->GetSupportDirectory(), '/', lang,
6319
0
                  "_build_database.json");
6320
0
}
6321
6322
std::string cmGeneratorTarget::GetSwiftPackageName() const
6323
0
{
6324
0
  std::string packageName;
6325
0
  if (cmValue projectName = this->GetProperty("Swift_PACKAGE_NAME")) {
6326
0
    packageName = *projectName;
6327
0
  } else if (this->GetPolicyStatusCMP0216() == cmPolicies::NEW) {
6328
0
    packageName = this->Makefile->GetSafeDefinition("PROJECT_NAME");
6329
0
  }
6330
0
  return packageName;
6331
0
}
6332
6333
std::string cmGeneratorTarget::GetSwiftModuleName() const
6334
0
{
6335
0
  if (cmValue name = this->GetProperty("Swift_MODULE_NAME")) {
6336
0
    return *name;
6337
0
  }
6338
  // Hyphens are not valid in Swift module identifiers.
6339
0
  std::string name = this->GetName();
6340
0
  std::replace(name.begin(), name.end(), '-', '_');
6341
0
  return name;
6342
0
}
6343
6344
std::string cmGeneratorTarget::GetSwiftModuleFileName() const
6345
0
{
6346
0
  std::string moduleFilename = this->GetPropertyOrDefault(
6347
0
    "Swift_MODULE", this->GetSwiftModuleName() + ".swiftmodule");
6348
0
  if (this->GetPolicyStatusCMP0195() == cmPolicies::NEW) {
6349
0
    if (cmValue moduleTriple =
6350
0
          this->Makefile->GetDefinition("CMAKE_Swift_MODULE_TRIPLE")) {
6351
0
      moduleFilename = cmStrCat(std::move(moduleFilename), '/', *moduleTriple,
6352
0
                                ".swiftmodule");
6353
0
    }
6354
0
  }
6355
0
  return moduleFilename;
6356
0
}
6357
6358
std::string cmGeneratorTarget::GetSwiftModuleDirectory(
6359
  std::string const& config) const
6360
0
{
6361
  // This is like the *_OUTPUT_DIRECTORY properties except that we don't have a
6362
  // separate per-configuration target property.
6363
  //
6364
  // The property expands generator expressions. Multi-config generators append
6365
  // a per-configuration subdirectory to the specified directory unless a
6366
  // generator expression is used.
6367
0
  bool appendConfigDir = true;
6368
0
  std::string moduleDirectory;
6369
6370
0
  if (cmValue value = this->GetProperty("Swift_MODULE_DIRECTORY")) {
6371
0
    moduleDirectory = cmGeneratorExpression::Evaluate(
6372
0
      *value, this->LocalGenerator, config, this);
6373
0
    appendConfigDir = *value == moduleDirectory;
6374
0
  }
6375
0
  if (moduleDirectory.empty()) {
6376
0
    moduleDirectory = this->LocalGenerator->GetCurrentBinaryDirectory();
6377
0
  }
6378
0
  if (appendConfigDir) {
6379
0
    this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
6380
0
      "/", config, "", moduleDirectory);
6381
0
  }
6382
0
  return moduleDirectory;
6383
0
}
6384
6385
std::string cmGeneratorTarget::GetSwiftModulePath(
6386
  std::string const& config) const
6387
0
{
6388
0
  return cmStrCat(this->GetSwiftModuleDirectory(config), '/',
6389
0
                  this->GetSwiftModuleFileName());
6390
0
}
6391
6392
std::string cmGeneratorTarget::GetPropertyOrDefault(
6393
  std::string const& property, std::string defaultValue) const
6394
0
{
6395
0
  if (cmValue name = this->GetProperty(property)) {
6396
0
    return *name;
6397
0
  }
6398
0
  return defaultValue;
6399
0
}