Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Driver/ToolChain.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ToolChain.cpp - Collections of tools for one platform --------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include "clang/Driver/ToolChain.h"
10
#include "ToolChains/Arch/AArch64.h"
11
#include "ToolChains/Arch/ARM.h"
12
#include "ToolChains/Clang.h"
13
#include "ToolChains/CommonArgs.h"
14
#include "ToolChains/Flang.h"
15
#include "ToolChains/InterfaceStubs.h"
16
#include "clang/Basic/ObjCRuntime.h"
17
#include "clang/Basic/Sanitizers.h"
18
#include "clang/Config/config.h"
19
#include "clang/Driver/Action.h"
20
#include "clang/Driver/Driver.h"
21
#include "clang/Driver/DriverDiagnostic.h"
22
#include "clang/Driver/InputInfo.h"
23
#include "clang/Driver/Job.h"
24
#include "clang/Driver/Options.h"
25
#include "clang/Driver/SanitizerArgs.h"
26
#include "clang/Driver/XRayArgs.h"
27
#include "llvm/ADT/STLExtras.h"
28
#include "llvm/ADT/SmallString.h"
29
#include "llvm/ADT/StringExtras.h"
30
#include "llvm/ADT/StringRef.h"
31
#include "llvm/ADT/Twine.h"
32
#include "llvm/Config/llvm-config.h"
33
#include "llvm/MC/MCTargetOptions.h"
34
#include "llvm/MC/TargetRegistry.h"
35
#include "llvm/Option/Arg.h"
36
#include "llvm/Option/ArgList.h"
37
#include "llvm/Option/OptTable.h"
38
#include "llvm/Option/Option.h"
39
#include "llvm/Support/ErrorHandling.h"
40
#include "llvm/Support/FileSystem.h"
41
#include "llvm/Support/FileUtilities.h"
42
#include "llvm/Support/Path.h"
43
#include "llvm/Support/VersionTuple.h"
44
#include "llvm/Support/VirtualFileSystem.h"
45
#include "llvm/TargetParser/AArch64TargetParser.h"
46
#include "llvm/TargetParser/TargetParser.h"
47
#include "llvm/TargetParser/Triple.h"
48
#include <cassert>
49
#include <cstddef>
50
#include <cstring>
51
#include <string>
52
53
using namespace clang;
54
using namespace driver;
55
using namespace tools;
56
using namespace llvm;
57
using namespace llvm::opt;
58
59
0
static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
60
0
  return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
61
0
                         options::OPT_fno_rtti, options::OPT_frtti);
62
0
}
63
64
static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
65
                                             const llvm::Triple &Triple,
66
0
                                             const Arg *CachedRTTIArg) {
67
  // Explicit rtti/no-rtti args
68
0
  if (CachedRTTIArg) {
69
0
    if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
70
0
      return ToolChain::RM_Enabled;
71
0
    else
72
0
      return ToolChain::RM_Disabled;
73
0
  }
74
75
  // -frtti is default, except for the PS4/PS5 and DriverKit.
76
0
  bool NoRTTI = Triple.isPS() || Triple.isDriverKit();
77
0
  return NoRTTI ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
78
0
}
79
80
ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
81
                     const ArgList &Args)
82
    : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
83
0
      CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
84
0
  auto addIfExists = [this](path_list &List, const std::string &Path) {
85
0
    if (getVFS().exists(Path))
86
0
      List.push_back(Path);
87
0
  };
88
89
0
  if (std::optional<std::string> Path = getRuntimePath())
90
0
    getLibraryPaths().push_back(*Path);
91
0
  if (std::optional<std::string> Path = getStdlibPath())
92
0
    getFilePaths().push_back(*Path);
93
0
  for (const auto &Path : getArchSpecificLibPaths())
94
0
    addIfExists(getFilePaths(), Path);
95
0
}
96
97
llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
98
0
ToolChain::executeToolChainProgram(StringRef Executable) const {
99
0
  llvm::SmallString<64> OutputFile;
100
0
  llvm::sys::fs::createTemporaryFile("toolchain-program", "txt", OutputFile);
101
0
  llvm::FileRemover OutputRemover(OutputFile.c_str());
102
0
  std::optional<llvm::StringRef> Redirects[] = {
103
0
      {""},
104
0
      OutputFile.str(),
105
0
      {""},
106
0
  };
107
108
0
  std::string ErrorMessage;
109
0
  if (llvm::sys::ExecuteAndWait(Executable, {}, {}, Redirects,
110
0
                                /* SecondsToWait */ 0,
111
0
                                /*MemoryLimit*/ 0, &ErrorMessage))
112
0
    return llvm::createStringError(std::error_code(),
113
0
                                   Executable + ": " + ErrorMessage);
114
115
0
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> OutputBuf =
116
0
      llvm::MemoryBuffer::getFile(OutputFile.c_str());
117
0
  if (!OutputBuf)
118
0
    return llvm::createStringError(OutputBuf.getError(),
119
0
                                   "Failed to read stdout of " + Executable +
120
0
                                       ": " + OutputBuf.getError().message());
121
0
  return std::move(*OutputBuf);
122
0
}
123
124
0
void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
125
0
  Triple.setEnvironment(Env);
126
0
  if (EffectiveTriple != llvm::Triple())
127
0
    EffectiveTriple.setEnvironment(Env);
128
0
}
129
130
0
ToolChain::~ToolChain() = default;
131
132
0
llvm::vfs::FileSystem &ToolChain::getVFS() const {
133
0
  return getDriver().getVFS();
134
0
}
135
136
0
bool ToolChain::useIntegratedAs() const {
137
0
  return Args.hasFlag(options::OPT_fintegrated_as,
138
0
                      options::OPT_fno_integrated_as,
139
0
                      IsIntegratedAssemblerDefault());
140
0
}
141
142
0
bool ToolChain::useIntegratedBackend() const {
143
0
  assert(
144
0
      ((IsIntegratedBackendDefault() && IsIntegratedBackendSupported()) ||
145
0
       (!IsIntegratedBackendDefault() || IsNonIntegratedBackendSupported())) &&
146
0
      "(Non-)integrated backend set incorrectly!");
147
148
0
  bool IBackend = Args.hasFlag(options::OPT_fintegrated_objemitter,
149
0
                               options::OPT_fno_integrated_objemitter,
150
0
                               IsIntegratedBackendDefault());
151
152
  // Diagnose when integrated-objemitter options are not supported by this
153
  // toolchain.
154
0
  unsigned DiagID;
155
0
  if ((IBackend && !IsIntegratedBackendSupported()) ||
156
0
      (!IBackend && !IsNonIntegratedBackendSupported()))
157
0
    DiagID = clang::diag::err_drv_unsupported_opt_for_target;
158
0
  else
159
0
    DiagID = clang::diag::warn_drv_unsupported_opt_for_target;
160
0
  Arg *A = Args.getLastArg(options::OPT_fno_integrated_objemitter);
161
0
  if (A && !IsNonIntegratedBackendSupported())
162
0
    D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
163
0
  A = Args.getLastArg(options::OPT_fintegrated_objemitter);
164
0
  if (A && !IsIntegratedBackendSupported())
165
0
    D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
166
167
0
  return IBackend;
168
0
}
169
170
0
bool ToolChain::useRelaxRelocations() const {
171
0
  return ENABLE_X86_RELAX_RELOCATIONS;
172
0
}
173
174
0
bool ToolChain::defaultToIEEELongDouble() const {
175
0
  return PPC_LINUX_DEFAULT_IEEELONGDOUBLE && getTriple().isOSLinux();
176
0
}
177
178
static void getAArch64MultilibFlags(const Driver &D,
179
                                          const llvm::Triple &Triple,
180
                                          const llvm::opt::ArgList &Args,
181
0
                                          Multilib::flags_list &Result) {
182
0
  std::vector<StringRef> Features;
183
0
  tools::aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, false);
184
0
  const auto UnifiedFeatures = tools::unifyTargetFeatures(Features);
185
0
  llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(),
186
0
                                       UnifiedFeatures.end());
187
0
  std::vector<std::string> MArch;
188
0
  for (const auto &Ext : AArch64::Extensions)
189
0
    if (FeatureSet.contains(Ext.Feature))
190
0
      MArch.push_back(Ext.Name.str());
191
0
  for (const auto &Ext : AArch64::Extensions)
192
0
    if (FeatureSet.contains(Ext.NegFeature))
193
0
      MArch.push_back(("no" + Ext.Name).str());
194
0
  MArch.insert(MArch.begin(), ("-march=" + Triple.getArchName()).str());
195
0
  Result.push_back(llvm::join(MArch, "+"));
196
0
}
197
198
static void getARMMultilibFlags(const Driver &D,
199
                                      const llvm::Triple &Triple,
200
                                      const llvm::opt::ArgList &Args,
201
0
                                      Multilib::flags_list &Result) {
202
0
  std::vector<StringRef> Features;
203
0
  llvm::ARM::FPUKind FPUKind = tools::arm::getARMTargetFeatures(
204
0
      D, Triple, Args, Features, false /*ForAs*/, true /*ForMultilib*/);
205
0
  const auto UnifiedFeatures = tools::unifyTargetFeatures(Features);
206
0
  llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(),
207
0
                                       UnifiedFeatures.end());
208
0
  std::vector<std::string> MArch;
209
0
  for (const auto &Ext : ARM::ARCHExtNames)
210
0
    if (FeatureSet.contains(Ext.Feature))
211
0
      MArch.push_back(Ext.Name.str());
212
0
  for (const auto &Ext : ARM::ARCHExtNames)
213
0
    if (FeatureSet.contains(Ext.NegFeature))
214
0
      MArch.push_back(("no" + Ext.Name).str());
215
0
  MArch.insert(MArch.begin(), ("-march=" + Triple.getArchName()).str());
216
0
  Result.push_back(llvm::join(MArch, "+"));
217
218
0
  switch (FPUKind) {
219
0
#define ARM_FPU(NAME, KIND, VERSION, NEON_SUPPORT, RESTRICTION)                \
220
0
  case llvm::ARM::KIND:                                                        \
221
0
    Result.push_back("-mfpu=" NAME);                                           \
222
0
    break;
223
0
#include "llvm/TargetParser/ARMTargetParser.def"
224
0
  default:
225
0
    llvm_unreachable("Invalid FPUKind");
226
0
  }
227
228
0
  switch (arm::getARMFloatABI(D, Triple, Args)) {
229
0
  case arm::FloatABI::Soft:
230
0
    Result.push_back("-mfloat-abi=soft");
231
0
    break;
232
0
  case arm::FloatABI::SoftFP:
233
0
    Result.push_back("-mfloat-abi=softfp");
234
0
    break;
235
0
  case arm::FloatABI::Hard:
236
0
    Result.push_back("-mfloat-abi=hard");
237
0
    break;
238
0
  case arm::FloatABI::Invalid:
239
0
    llvm_unreachable("Invalid float ABI");
240
0
  }
241
0
}
242
243
Multilib::flags_list
244
0
ToolChain::getMultilibFlags(const llvm::opt::ArgList &Args) const {
245
0
  using namespace clang::driver::options;
246
247
0
  std::vector<std::string> Result;
248
0
  const llvm::Triple Triple(ComputeEffectiveClangTriple(Args));
249
0
  Result.push_back("--target=" + Triple.str());
250
251
0
  switch (Triple.getArch()) {
252
0
  case llvm::Triple::aarch64:
253
0
  case llvm::Triple::aarch64_32:
254
0
  case llvm::Triple::aarch64_be:
255
0
    getAArch64MultilibFlags(D, Triple, Args, Result);
256
0
    break;
257
0
  case llvm::Triple::arm:
258
0
  case llvm::Triple::armeb:
259
0
  case llvm::Triple::thumb:
260
0
  case llvm::Triple::thumbeb:
261
0
    getARMMultilibFlags(D, Triple, Args, Result);
262
0
    break;
263
0
  default:
264
0
    break;
265
0
  }
266
267
  // Sort and remove duplicates.
268
0
  std::sort(Result.begin(), Result.end());
269
0
  Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
270
0
  return Result;
271
0
}
272
273
SanitizerArgs
274
0
ToolChain::getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const {
275
0
  SanitizerArgs SanArgs(*this, JobArgs, !SanitizerArgsChecked);
276
0
  SanitizerArgsChecked = true;
277
0
  return SanArgs;
278
0
}
279
280
0
const XRayArgs& ToolChain::getXRayArgs() const {
281
0
  if (!XRayArguments)
282
0
    XRayArguments.reset(new XRayArgs(*this, Args));
283
0
  return *XRayArguments;
284
0
}
285
286
namespace {
287
288
struct DriverSuffix {
289
  const char *Suffix;
290
  const char *ModeFlag;
291
};
292
293
} // namespace
294
295
0
static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
296
  // A list of known driver suffixes. Suffixes are compared against the
297
  // program name in order. If there is a match, the frontend type is updated as
298
  // necessary by applying the ModeFlag.
299
0
  static const DriverSuffix DriverSuffixes[] = {
300
0
      {"clang", nullptr},
301
0
      {"clang++", "--driver-mode=g++"},
302
0
      {"clang-c++", "--driver-mode=g++"},
303
0
      {"clang-cc", nullptr},
304
0
      {"clang-cpp", "--driver-mode=cpp"},
305
0
      {"clang-g++", "--driver-mode=g++"},
306
0
      {"clang-gcc", nullptr},
307
0
      {"clang-cl", "--driver-mode=cl"},
308
0
      {"cc", nullptr},
309
0
      {"cpp", "--driver-mode=cpp"},
310
0
      {"cl", "--driver-mode=cl"},
311
0
      {"++", "--driver-mode=g++"},
312
0
      {"flang", "--driver-mode=flang"},
313
0
      {"clang-dxc", "--driver-mode=dxc"},
314
0
  };
315
316
0
  for (const auto &DS : DriverSuffixes) {
317
0
    StringRef Suffix(DS.Suffix);
318
0
    if (ProgName.ends_with(Suffix)) {
319
0
      Pos = ProgName.size() - Suffix.size();
320
0
      return &DS;
321
0
    }
322
0
  }
323
0
  return nullptr;
324
0
}
325
326
/// Normalize the program name from argv[0] by stripping the file extension if
327
/// present and lower-casing the string on Windows.
328
0
static std::string normalizeProgramName(llvm::StringRef Argv0) {
329
0
  std::string ProgName = std::string(llvm::sys::path::filename(Argv0));
330
0
  if (is_style_windows(llvm::sys::path::Style::native)) {
331
    // Transform to lowercase for case insensitive file systems.
332
0
    std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(),
333
0
                   ::tolower);
334
0
  }
335
0
  return ProgName;
336
0
}
337
338
0
static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
339
  // Try to infer frontend type and default target from the program name by
340
  // comparing it against DriverSuffixes in order.
341
342
  // If there is a match, the function tries to identify a target as prefix.
343
  // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
344
  // prefix "x86_64-linux". If such a target prefix is found, it may be
345
  // added via -target as implicit first argument.
346
0
  const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
347
348
0
  if (!DS && ProgName.ends_with(".exe")) {
349
    // Try again after stripping the executable suffix:
350
    // clang++.exe -> clang++
351
0
    ProgName = ProgName.drop_back(StringRef(".exe").size());
352
0
    DS = FindDriverSuffix(ProgName, Pos);
353
0
  }
354
355
0
  if (!DS) {
356
    // Try again after stripping any trailing version number:
357
    // clang++3.5 -> clang++
358
0
    ProgName = ProgName.rtrim("0123456789.");
359
0
    DS = FindDriverSuffix(ProgName, Pos);
360
0
  }
361
362
0
  if (!DS) {
363
    // Try again after stripping trailing -component.
364
    // clang++-tot -> clang++
365
0
    ProgName = ProgName.slice(0, ProgName.rfind('-'));
366
0
    DS = FindDriverSuffix(ProgName, Pos);
367
0
  }
368
0
  return DS;
369
0
}
370
371
ParsedClangName
372
0
ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
373
0
  std::string ProgName = normalizeProgramName(PN);
374
0
  size_t SuffixPos;
375
0
  const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
376
0
  if (!DS)
377
0
    return {};
378
0
  size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
379
380
0
  size_t LastComponent = ProgName.rfind('-', SuffixPos);
381
0
  if (LastComponent == std::string::npos)
382
0
    return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
383
0
  std::string ModeSuffix = ProgName.substr(LastComponent + 1,
384
0
                                           SuffixEnd - LastComponent - 1);
385
386
  // Infer target from the prefix.
387
0
  StringRef Prefix(ProgName);
388
0
  Prefix = Prefix.slice(0, LastComponent);
389
0
  std::string IgnoredError;
390
0
  bool IsRegistered =
391
0
      llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError);
392
0
  return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
393
0
                         IsRegistered};
394
0
}
395
396
0
StringRef ToolChain::getDefaultUniversalArchName() const {
397
  // In universal driver terms, the arch name accepted by -arch isn't exactly
398
  // the same as the ones that appear in the triple. Roughly speaking, this is
399
  // an inverse of the darwin::getArchTypeForDarwinArchName() function.
400
0
  switch (Triple.getArch()) {
401
0
  case llvm::Triple::aarch64: {
402
0
    if (getTriple().isArm64e())
403
0
      return "arm64e";
404
0
    return "arm64";
405
0
  }
406
0
  case llvm::Triple::aarch64_32:
407
0
    return "arm64_32";
408
0
  case llvm::Triple::ppc:
409
0
    return "ppc";
410
0
  case llvm::Triple::ppcle:
411
0
    return "ppcle";
412
0
  case llvm::Triple::ppc64:
413
0
    return "ppc64";
414
0
  case llvm::Triple::ppc64le:
415
0
    return "ppc64le";
416
0
  default:
417
0
    return Triple.getArchName();
418
0
  }
419
0
}
420
421
0
std::string ToolChain::getInputFilename(const InputInfo &Input) const {
422
0
  return Input.getFilename();
423
0
}
424
425
ToolChain::UnwindTableLevel
426
0
ToolChain::getDefaultUnwindTableLevel(const ArgList &Args) const {
427
0
  return UnwindTableLevel::None;
428
0
}
429
430
0
unsigned ToolChain::GetDefaultDwarfVersion() const {
431
  // TODO: Remove the RISC-V special case when R_RISCV_SET_ULEB128 linker
432
  // support becomes more widely available.
433
0
  return getTriple().isRISCV() ? 4 : 5;
434
0
}
435
436
0
Tool *ToolChain::getClang() const {
437
0
  if (!Clang)
438
0
    Clang.reset(new tools::Clang(*this, useIntegratedBackend()));
439
0
  return Clang.get();
440
0
}
441
442
0
Tool *ToolChain::getFlang() const {
443
0
  if (!Flang)
444
0
    Flang.reset(new tools::Flang(*this));
445
0
  return Flang.get();
446
0
}
447
448
0
Tool *ToolChain::buildAssembler() const {
449
0
  return new tools::ClangAs(*this);
450
0
}
451
452
0
Tool *ToolChain::buildLinker() const {
453
0
  llvm_unreachable("Linking is not supported by this toolchain");
454
0
}
455
456
0
Tool *ToolChain::buildStaticLibTool() const {
457
0
  llvm_unreachable("Creating static lib is not supported by this toolchain");
458
0
}
459
460
0
Tool *ToolChain::getAssemble() const {
461
0
  if (!Assemble)
462
0
    Assemble.reset(buildAssembler());
463
0
  return Assemble.get();
464
0
}
465
466
0
Tool *ToolChain::getClangAs() const {
467
0
  if (!Assemble)
468
0
    Assemble.reset(new tools::ClangAs(*this));
469
0
  return Assemble.get();
470
0
}
471
472
0
Tool *ToolChain::getLink() const {
473
0
  if (!Link)
474
0
    Link.reset(buildLinker());
475
0
  return Link.get();
476
0
}
477
478
0
Tool *ToolChain::getStaticLibTool() const {
479
0
  if (!StaticLibTool)
480
0
    StaticLibTool.reset(buildStaticLibTool());
481
0
  return StaticLibTool.get();
482
0
}
483
484
0
Tool *ToolChain::getIfsMerge() const {
485
0
  if (!IfsMerge)
486
0
    IfsMerge.reset(new tools::ifstool::Merger(*this));
487
0
  return IfsMerge.get();
488
0
}
489
490
0
Tool *ToolChain::getOffloadBundler() const {
491
0
  if (!OffloadBundler)
492
0
    OffloadBundler.reset(new tools::OffloadBundler(*this));
493
0
  return OffloadBundler.get();
494
0
}
495
496
0
Tool *ToolChain::getOffloadPackager() const {
497
0
  if (!OffloadPackager)
498
0
    OffloadPackager.reset(new tools::OffloadPackager(*this));
499
0
  return OffloadPackager.get();
500
0
}
501
502
0
Tool *ToolChain::getLinkerWrapper() const {
503
0
  if (!LinkerWrapper)
504
0
    LinkerWrapper.reset(new tools::LinkerWrapper(*this, getLink()));
505
0
  return LinkerWrapper.get();
506
0
}
507
508
0
Tool *ToolChain::getTool(Action::ActionClass AC) const {
509
0
  switch (AC) {
510
0
  case Action::AssembleJobClass:
511
0
    return getAssemble();
512
513
0
  case Action::IfsMergeJobClass:
514
0
    return getIfsMerge();
515
516
0
  case Action::LinkJobClass:
517
0
    return getLink();
518
519
0
  case Action::StaticLibJobClass:
520
0
    return getStaticLibTool();
521
522
0
  case Action::InputClass:
523
0
  case Action::BindArchClass:
524
0
  case Action::OffloadClass:
525
0
  case Action::LipoJobClass:
526
0
  case Action::DsymutilJobClass:
527
0
  case Action::VerifyDebugInfoJobClass:
528
0
  case Action::BinaryAnalyzeJobClass:
529
0
    llvm_unreachable("Invalid tool kind.");
530
531
0
  case Action::CompileJobClass:
532
0
  case Action::PrecompileJobClass:
533
0
  case Action::PreprocessJobClass:
534
0
  case Action::ExtractAPIJobClass:
535
0
  case Action::AnalyzeJobClass:
536
0
  case Action::MigrateJobClass:
537
0
  case Action::VerifyPCHJobClass:
538
0
  case Action::BackendJobClass:
539
0
    return getClang();
540
541
0
  case Action::OffloadBundlingJobClass:
542
0
  case Action::OffloadUnbundlingJobClass:
543
0
    return getOffloadBundler();
544
545
0
  case Action::OffloadPackagerJobClass:
546
0
    return getOffloadPackager();
547
0
  case Action::LinkerWrapperJobClass:
548
0
    return getLinkerWrapper();
549
0
  }
550
551
0
  llvm_unreachable("Invalid tool kind.");
552
0
}
553
554
static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
555
0
                                             const ArgList &Args) {
556
0
  const llvm::Triple &Triple = TC.getTriple();
557
0
  bool IsWindows = Triple.isOSWindows();
558
559
0
  if (TC.isBareMetal())
560
0
    return Triple.getArchName();
561
562
0
  if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
563
0
    return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
564
0
               ? "armhf"
565
0
               : "arm";
566
567
  // For historic reasons, Android library is using i686 instead of i386.
568
0
  if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
569
0
    return "i686";
570
571
0
  if (TC.getArch() == llvm::Triple::x86_64 && Triple.isX32())
572
0
    return "x32";
573
574
0
  return llvm::Triple::getArchTypeName(TC.getArch());
575
0
}
576
577
0
StringRef ToolChain::getOSLibName() const {
578
0
  if (Triple.isOSDarwin())
579
0
    return "darwin";
580
581
0
  switch (Triple.getOS()) {
582
0
  case llvm::Triple::FreeBSD:
583
0
    return "freebsd";
584
0
  case llvm::Triple::NetBSD:
585
0
    return "netbsd";
586
0
  case llvm::Triple::OpenBSD:
587
0
    return "openbsd";
588
0
  case llvm::Triple::Solaris:
589
0
    return "sunos";
590
0
  case llvm::Triple::AIX:
591
0
    return "aix";
592
0
  default:
593
0
    return getOS();
594
0
  }
595
0
}
596
597
0
std::string ToolChain::getCompilerRTPath() const {
598
0
  SmallString<128> Path(getDriver().ResourceDir);
599
0
  if (isBareMetal()) {
600
0
    llvm::sys::path::append(Path, "lib", getOSLibName());
601
0
    if (!SelectedMultilibs.empty()) {
602
0
      Path += SelectedMultilibs.back().gccSuffix();
603
0
    }
604
0
  } else if (Triple.isOSUnknown()) {
605
0
    llvm::sys::path::append(Path, "lib");
606
0
  } else {
607
0
    llvm::sys::path::append(Path, "lib", getOSLibName());
608
0
  }
609
0
  return std::string(Path.str());
610
0
}
611
612
std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
613
                                             StringRef Component,
614
0
                                             FileType Type) const {
615
0
  std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type);
616
0
  return llvm::sys::path::filename(CRTAbsolutePath).str();
617
0
}
618
619
std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args,
620
                                               StringRef Component,
621
                                               FileType Type,
622
0
                                               bool AddArch) const {
623
0
  const llvm::Triple &TT = getTriple();
624
0
  bool IsITANMSVCWindows =
625
0
      TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
626
627
0
  const char *Prefix =
628
0
      IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
629
0
  const char *Suffix;
630
0
  switch (Type) {
631
0
  case ToolChain::FT_Object:
632
0
    Suffix = IsITANMSVCWindows ? ".obj" : ".o";
633
0
    break;
634
0
  case ToolChain::FT_Static:
635
0
    Suffix = IsITANMSVCWindows ? ".lib" : ".a";
636
0
    break;
637
0
  case ToolChain::FT_Shared:
638
0
    Suffix = TT.isOSWindows()
639
0
                 ? (TT.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
640
0
                 : ".so";
641
0
    break;
642
0
  }
643
644
0
  std::string ArchAndEnv;
645
0
  if (AddArch) {
646
0
    StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
647
0
    const char *Env = TT.isAndroid() ? "-android" : "";
648
0
    ArchAndEnv = ("-" + Arch + Env).str();
649
0
  }
650
0
  return (Prefix + Twine("clang_rt.") + Component + ArchAndEnv + Suffix).str();
651
0
}
652
653
std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
654
0
                                     FileType Type) const {
655
  // Check for runtime files in the new layout without the architecture first.
656
0
  std::string CRTBasename =
657
0
      buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/false);
658
0
  for (const auto &LibPath : getLibraryPaths()) {
659
0
    SmallString<128> P(LibPath);
660
0
    llvm::sys::path::append(P, CRTBasename);
661
0
    if (getVFS().exists(P))
662
0
      return std::string(P.str());
663
0
  }
664
665
  // Fall back to the old expected compiler-rt name if the new one does not
666
  // exist.
667
0
  CRTBasename =
668
0
      buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/true);
669
0
  SmallString<128> Path(getCompilerRTPath());
670
0
  llvm::sys::path::append(Path, CRTBasename);
671
0
  return std::string(Path.str());
672
0
}
673
674
const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
675
                                              StringRef Component,
676
0
                                              FileType Type) const {
677
0
  return Args.MakeArgString(getCompilerRT(Args, Component, Type));
678
0
}
679
680
// Android target triples contain a target version. If we don't have libraries
681
// for the exact target version, we should fall back to the next newest version
682
// or a versionless path, if any.
683
std::optional<std::string>
684
0
ToolChain::getFallbackAndroidTargetPath(StringRef BaseDir) const {
685
0
  llvm::Triple TripleWithoutLevel(getTriple());
686
0
  TripleWithoutLevel.setEnvironmentName("android"); // remove any version number
687
0
  const std::string &TripleWithoutLevelStr = TripleWithoutLevel.str();
688
0
  unsigned TripleVersion = getTriple().getEnvironmentVersion().getMajor();
689
0
  unsigned BestVersion = 0;
690
691
0
  SmallString<32> TripleDir;
692
0
  bool UsingUnversionedDir = false;
693
0
  std::error_code EC;
694
0
  for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(BaseDir, EC), LE;
695
0
       !EC && LI != LE; LI = LI.increment(EC)) {
696
0
    StringRef DirName = llvm::sys::path::filename(LI->path());
697
0
    StringRef DirNameSuffix = DirName;
698
0
    if (DirNameSuffix.consume_front(TripleWithoutLevelStr)) {
699
0
      if (DirNameSuffix.empty() && TripleDir.empty()) {
700
0
        TripleDir = DirName;
701
0
        UsingUnversionedDir = true;
702
0
      } else {
703
0
        unsigned Version;
704
0
        if (!DirNameSuffix.getAsInteger(10, Version) && Version > BestVersion &&
705
0
            Version < TripleVersion) {
706
0
          BestVersion = Version;
707
0
          TripleDir = DirName;
708
0
          UsingUnversionedDir = false;
709
0
        }
710
0
      }
711
0
    }
712
0
  }
713
714
0
  if (TripleDir.empty())
715
0
    return {};
716
717
0
  SmallString<128> P(BaseDir);
718
0
  llvm::sys::path::append(P, TripleDir);
719
0
  if (UsingUnversionedDir)
720
0
    D.Diag(diag::warn_android_unversioned_fallback) << P << getTripleString();
721
0
  return std::string(P);
722
0
}
723
724
std::optional<std::string>
725
0
ToolChain::getTargetSubDirPath(StringRef BaseDir) const {
726
0
  auto getPathForTriple =
727
0
      [&](const llvm::Triple &Triple) -> std::optional<std::string> {
728
0
    SmallString<128> P(BaseDir);
729
0
    llvm::sys::path::append(P, Triple.str());
730
0
    if (getVFS().exists(P))
731
0
      return std::string(P);
732
0
    return {};
733
0
  };
734
735
0
  if (auto Path = getPathForTriple(getTriple()))
736
0
    return *Path;
737
738
  // When building with per target runtime directories, various ways of naming
739
  // the Arm architecture may have been normalised to simply "arm".
740
  // For example "armv8l" (Armv8 AArch32 little endian) is replaced with "arm".
741
  // Since an armv8l system can use libraries built for earlier architecture
742
  // versions assuming endian and float ABI match.
743
  //
744
  // Original triple: armv8l-unknown-linux-gnueabihf
745
  //  Runtime triple: arm-unknown-linux-gnueabihf
746
  //
747
  // We do not do this for armeb (big endian) because doing so could make us
748
  // select little endian libraries. In addition, all known armeb triples only
749
  // use the "armeb" architecture name.
750
  //
751
  // M profile Arm is bare metal and we know they will not be using the per
752
  // target runtime directory layout.
753
0
  if (getTriple().getArch() == Triple::arm && !getTriple().isArmMClass()) {
754
0
    llvm::Triple ArmTriple = getTriple();
755
0
    ArmTriple.setArch(Triple::arm);
756
0
    if (auto Path = getPathForTriple(ArmTriple))
757
0
      return *Path;
758
0
  }
759
760
0
  if (getTriple().isAndroid())
761
0
    return getFallbackAndroidTargetPath(BaseDir);
762
763
0
  return {};
764
0
}
765
766
0
std::optional<std::string> ToolChain::getRuntimePath() const {
767
0
  SmallString<128> P(D.ResourceDir);
768
0
  llvm::sys::path::append(P, "lib");
769
0
  return getTargetSubDirPath(P);
770
0
}
771
772
0
std::optional<std::string> ToolChain::getStdlibPath() const {
773
0
  SmallString<128> P(D.Dir);
774
0
  llvm::sys::path::append(P, "..", "lib");
775
0
  return getTargetSubDirPath(P);
776
0
}
777
778
0
ToolChain::path_list ToolChain::getArchSpecificLibPaths() const {
779
0
  path_list Paths;
780
781
0
  auto AddPath = [&](const ArrayRef<StringRef> &SS) {
782
0
    SmallString<128> Path(getDriver().ResourceDir);
783
0
    llvm::sys::path::append(Path, "lib");
784
0
    for (auto &S : SS)
785
0
      llvm::sys::path::append(Path, S);
786
0
    Paths.push_back(std::string(Path.str()));
787
0
  };
788
789
0
  AddPath({getTriple().str()});
790
0
  AddPath({getOSLibName(), llvm::Triple::getArchTypeName(getArch())});
791
0
  return Paths;
792
0
}
793
794
0
bool ToolChain::needsProfileRT(const ArgList &Args) {
795
0
  if (Args.hasArg(options::OPT_noprofilelib))
796
0
    return false;
797
798
0
  return Args.hasArg(options::OPT_fprofile_generate) ||
799
0
         Args.hasArg(options::OPT_fprofile_generate_EQ) ||
800
0
         Args.hasArg(options::OPT_fcs_profile_generate) ||
801
0
         Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
802
0
         Args.hasArg(options::OPT_fprofile_instr_generate) ||
803
0
         Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
804
0
         Args.hasArg(options::OPT_fcreate_profile) ||
805
0
         Args.hasArg(options::OPT_forder_file_instrumentation);
806
0
}
807
808
0
bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
809
0
  return Args.hasArg(options::OPT_coverage) ||
810
0
         Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
811
0
                      false);
812
0
}
813
814
0
Tool *ToolChain::SelectTool(const JobAction &JA) const {
815
0
  if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
816
0
  if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
817
0
  Action::ActionClass AC = JA.getKind();
818
0
  if (AC == Action::AssembleJobClass && useIntegratedAs() &&
819
0
      !getTriple().isOSAIX())
820
0
    return getClangAs();
821
0
  return getTool(AC);
822
0
}
823
824
0
std::string ToolChain::GetFilePath(const char *Name) const {
825
0
  return D.GetFilePath(Name, *this);
826
0
}
827
828
0
std::string ToolChain::GetProgramPath(const char *Name) const {
829
0
  return D.GetProgramPath(Name, *this);
830
0
}
831
832
0
std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD) const {
833
0
  if (LinkerIsLLD)
834
0
    *LinkerIsLLD = false;
835
836
  // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
837
  // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
838
0
  const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
839
0
  StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
840
841
  // --ld-path= takes precedence over -fuse-ld= and specifies the executable
842
  // name. -B, COMPILER_PATH and PATH and consulted if the value does not
843
  // contain a path component separator.
844
  // -fuse-ld=lld can be used with --ld-path= to inform clang that the binary
845
  // that --ld-path= points to is lld.
846
0
  if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
847
0
    std::string Path(A->getValue());
848
0
    if (!Path.empty()) {
849
0
      if (llvm::sys::path::parent_path(Path).empty())
850
0
        Path = GetProgramPath(A->getValue());
851
0
      if (llvm::sys::fs::can_execute(Path)) {
852
0
        if (LinkerIsLLD)
853
0
          *LinkerIsLLD = UseLinker == "lld";
854
0
        return std::string(Path);
855
0
      }
856
0
    }
857
0
    getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
858
0
    return GetProgramPath(getDefaultLinker());
859
0
  }
860
  // If we're passed -fuse-ld= with no argument, or with the argument ld,
861
  // then use whatever the default system linker is.
862
0
  if (UseLinker.empty() || UseLinker == "ld") {
863
0
    const char *DefaultLinker = getDefaultLinker();
864
0
    if (llvm::sys::path::is_absolute(DefaultLinker))
865
0
      return std::string(DefaultLinker);
866
0
    else
867
0
      return GetProgramPath(DefaultLinker);
868
0
  }
869
870
  // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
871
  // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
872
  // to a relative path is surprising. This is more complex due to priorities
873
  // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
874
0
  if (UseLinker.contains('/'))
875
0
    getDriver().Diag(diag::warn_drv_fuse_ld_path);
876
877
0
  if (llvm::sys::path::is_absolute(UseLinker)) {
878
    // If we're passed what looks like an absolute path, don't attempt to
879
    // second-guess that.
880
0
    if (llvm::sys::fs::can_execute(UseLinker))
881
0
      return std::string(UseLinker);
882
0
  } else {
883
0
    llvm::SmallString<8> LinkerName;
884
0
    if (Triple.isOSDarwin())
885
0
      LinkerName.append("ld64.");
886
0
    else
887
0
      LinkerName.append("ld.");
888
0
    LinkerName.append(UseLinker);
889
890
0
    std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
891
0
    if (llvm::sys::fs::can_execute(LinkerPath)) {
892
0
      if (LinkerIsLLD)
893
0
        *LinkerIsLLD = UseLinker == "lld";
894
0
      return LinkerPath;
895
0
    }
896
0
  }
897
898
0
  if (A)
899
0
    getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
900
901
0
  return GetProgramPath(getDefaultLinker());
902
0
}
903
904
0
std::string ToolChain::GetStaticLibToolPath() const {
905
  // TODO: Add support for static lib archiving on Windows
906
0
  if (Triple.isOSDarwin())
907
0
    return GetProgramPath("libtool");
908
0
  return GetProgramPath("llvm-ar");
909
0
}
910
911
0
types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
912
0
  types::ID id = types::lookupTypeForExtension(Ext);
913
914
  // Flang always runs the preprocessor and has no notion of "preprocessed
915
  // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
916
  // them differently.
917
0
  if (D.IsFlangMode() && id == types::TY_PP_Fortran)
918
0
    id = types::TY_Fortran;
919
920
0
  return id;
921
0
}
922
923
0
bool ToolChain::HasNativeLLVMSupport() const {
924
0
  return false;
925
0
}
926
927
0
bool ToolChain::isCrossCompiling() const {
928
0
  llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
929
0
  switch (HostTriple.getArch()) {
930
  // The A32/T32/T16 instruction sets are not separate architectures in this
931
  // context.
932
0
  case llvm::Triple::arm:
933
0
  case llvm::Triple::armeb:
934
0
  case llvm::Triple::thumb:
935
0
  case llvm::Triple::thumbeb:
936
0
    return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
937
0
           getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
938
0
  default:
939
0
    return HostTriple.getArch() != getArch();
940
0
  }
941
0
}
942
943
0
ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
944
0
  return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
945
0
                     VersionTuple());
946
0
}
947
948
llvm::ExceptionHandling
949
0
ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
950
0
  return llvm::ExceptionHandling::None;
951
0
}
952
953
0
bool ToolChain::isThreadModelSupported(const StringRef Model) const {
954
0
  if (Model == "single") {
955
    // FIXME: 'single' is only supported on ARM and WebAssembly so far.
956
0
    return Triple.getArch() == llvm::Triple::arm ||
957
0
           Triple.getArch() == llvm::Triple::armeb ||
958
0
           Triple.getArch() == llvm::Triple::thumb ||
959
0
           Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
960
0
  } else if (Model == "posix")
961
0
    return true;
962
963
0
  return false;
964
0
}
965
966
std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
967
0
                                         types::ID InputType) const {
968
0
  switch (getTriple().getArch()) {
969
0
  default:
970
0
    return getTripleString();
971
972
0
  case llvm::Triple::x86_64: {
973
0
    llvm::Triple Triple = getTriple();
974
0
    if (!Triple.isOSBinFormatMachO())
975
0
      return getTripleString();
976
977
0
    if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
978
      // x86_64h goes in the triple. Other -march options just use the
979
      // vanilla triple we already have.
980
0
      StringRef MArch = A->getValue();
981
0
      if (MArch == "x86_64h")
982
0
        Triple.setArchName(MArch);
983
0
    }
984
0
    return Triple.getTriple();
985
0
  }
986
0
  case llvm::Triple::aarch64: {
987
0
    llvm::Triple Triple = getTriple();
988
0
    if (!Triple.isOSBinFormatMachO())
989
0
      return getTripleString();
990
991
0
    if (Triple.isArm64e())
992
0
      return getTripleString();
993
994
    // FIXME: older versions of ld64 expect the "arm64" component in the actual
995
    // triple string and query it to determine whether an LTO file can be
996
    // handled. Remove this when we don't care any more.
997
0
    Triple.setArchName("arm64");
998
0
    return Triple.getTriple();
999
0
  }
1000
0
  case llvm::Triple::aarch64_32:
1001
0
    return getTripleString();
1002
0
  case llvm::Triple::arm:
1003
0
  case llvm::Triple::armeb:
1004
0
  case llvm::Triple::thumb:
1005
0
  case llvm::Triple::thumbeb: {
1006
0
    llvm::Triple Triple = getTriple();
1007
0
    tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple);
1008
0
    tools::arm::setFloatABIInTriple(getDriver(), Args, Triple);
1009
0
    return Triple.getTriple();
1010
0
  }
1011
0
  }
1012
0
}
1013
1014
std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
1015
0
                                                   types::ID InputType) const {
1016
0
  return ComputeLLVMTriple(Args, InputType);
1017
0
}
1018
1019
0
std::string ToolChain::computeSysRoot() const {
1020
0
  return D.SysRoot;
1021
0
}
1022
1023
void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1024
0
                                          ArgStringList &CC1Args) const {
1025
  // Each toolchain should provide the appropriate include flags.
1026
0
}
1027
1028
void ToolChain::addClangTargetOptions(
1029
    const ArgList &DriverArgs, ArgStringList &CC1Args,
1030
0
    Action::OffloadKind DeviceOffloadKind) const {}
1031
1032
void ToolChain::addClangCC1ASTargetOptions(const ArgList &Args,
1033
0
                                           ArgStringList &CC1ASArgs) const {}
1034
1035
0
void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
1036
1037
void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
1038
0
                                 llvm::opt::ArgStringList &CmdArgs) const {
1039
0
  if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
1040
0
    return;
1041
1042
0
  CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
1043
0
}
1044
1045
ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
1046
0
    const ArgList &Args) const {
1047
0
  if (runtimeLibType)
1048
0
    return *runtimeLibType;
1049
1050
0
  const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
1051
0
  StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
1052
1053
  // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
1054
0
  if (LibName == "compiler-rt")
1055
0
    runtimeLibType = ToolChain::RLT_CompilerRT;
1056
0
  else if (LibName == "libgcc")
1057
0
    runtimeLibType = ToolChain::RLT_Libgcc;
1058
0
  else if (LibName == "platform")
1059
0
    runtimeLibType = GetDefaultRuntimeLibType();
1060
0
  else {
1061
0
    if (A)
1062
0
      getDriver().Diag(diag::err_drv_invalid_rtlib_name)
1063
0
          << A->getAsString(Args);
1064
1065
0
    runtimeLibType = GetDefaultRuntimeLibType();
1066
0
  }
1067
1068
0
  return *runtimeLibType;
1069
0
}
1070
1071
ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
1072
0
    const ArgList &Args) const {
1073
0
  if (unwindLibType)
1074
0
    return *unwindLibType;
1075
1076
0
  const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
1077
0
  StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
1078
1079
0
  if (LibName == "none")
1080
0
    unwindLibType = ToolChain::UNW_None;
1081
0
  else if (LibName == "platform" || LibName == "") {
1082
0
    ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
1083
0
    if (RtLibType == ToolChain::RLT_CompilerRT) {
1084
0
      if (getTriple().isAndroid() || getTriple().isOSAIX())
1085
0
        unwindLibType = ToolChain::UNW_CompilerRT;
1086
0
      else
1087
0
        unwindLibType = ToolChain::UNW_None;
1088
0
    } else if (RtLibType == ToolChain::RLT_Libgcc)
1089
0
      unwindLibType = ToolChain::UNW_Libgcc;
1090
0
  } else if (LibName == "libunwind") {
1091
0
    if (GetRuntimeLibType(Args) == RLT_Libgcc)
1092
0
      getDriver().Diag(diag::err_drv_incompatible_unwindlib);
1093
0
    unwindLibType = ToolChain::UNW_CompilerRT;
1094
0
  } else if (LibName == "libgcc")
1095
0
    unwindLibType = ToolChain::UNW_Libgcc;
1096
0
  else {
1097
0
    if (A)
1098
0
      getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
1099
0
          << A->getAsString(Args);
1100
1101
0
    unwindLibType = GetDefaultUnwindLibType();
1102
0
  }
1103
1104
0
  return *unwindLibType;
1105
0
}
1106
1107
0
ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
1108
0
  if (cxxStdlibType)
1109
0
    return *cxxStdlibType;
1110
1111
0
  const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
1112
0
  StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
1113
1114
  // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
1115
0
  if (LibName == "libc++")
1116
0
    cxxStdlibType = ToolChain::CST_Libcxx;
1117
0
  else if (LibName == "libstdc++")
1118
0
    cxxStdlibType = ToolChain::CST_Libstdcxx;
1119
0
  else if (LibName == "platform")
1120
0
    cxxStdlibType = GetDefaultCXXStdlibType();
1121
0
  else {
1122
0
    if (A)
1123
0
      getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1124
0
          << A->getAsString(Args);
1125
1126
0
    cxxStdlibType = GetDefaultCXXStdlibType();
1127
0
  }
1128
1129
0
  return *cxxStdlibType;
1130
0
}
1131
1132
/// Utility function to add a system include directory to CC1 arguments.
1133
/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
1134
                                            ArgStringList &CC1Args,
1135
0
                                            const Twine &Path) {
1136
0
  CC1Args.push_back("-internal-isystem");
1137
0
  CC1Args.push_back(DriverArgs.MakeArgString(Path));
1138
0
}
1139
1140
/// Utility function to add a system include directory with extern "C"
1141
/// semantics to CC1 arguments.
1142
///
1143
/// Note that this should be used rarely, and only for directories that
1144
/// historically and for legacy reasons are treated as having implicit extern
1145
/// "C" semantics. These semantics are *ignored* by and large today, but its
1146
/// important to preserve the preprocessor changes resulting from the
1147
/// classification.
1148
/*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
1149
                                                   ArgStringList &CC1Args,
1150
0
                                                   const Twine &Path) {
1151
0
  CC1Args.push_back("-internal-externc-isystem");
1152
0
  CC1Args.push_back(DriverArgs.MakeArgString(Path));
1153
0
}
1154
1155
void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
1156
                                                ArgStringList &CC1Args,
1157
0
                                                const Twine &Path) {
1158
0
  if (llvm::sys::fs::exists(Path))
1159
0
    addExternCSystemInclude(DriverArgs, CC1Args, Path);
1160
0
}
1161
1162
/// Utility function to add a list of system include directories to CC1.
1163
/*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
1164
                                             ArgStringList &CC1Args,
1165
0
                                             ArrayRef<StringRef> Paths) {
1166
0
  for (const auto &Path : Paths) {
1167
0
    CC1Args.push_back("-internal-isystem");
1168
0
    CC1Args.push_back(DriverArgs.MakeArgString(Path));
1169
0
  }
1170
0
}
1171
1172
/*static*/ std::string ToolChain::concat(StringRef Path, const Twine &A,
1173
                                         const Twine &B, const Twine &C,
1174
0
                                         const Twine &D) {
1175
0
  SmallString<128> Result(Path);
1176
0
  llvm::sys::path::append(Result, llvm::sys::path::Style::posix, A, B, C, D);
1177
0
  return std::string(Result);
1178
0
}
1179
1180
0
std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const {
1181
0
  std::error_code EC;
1182
0
  int MaxVersion = 0;
1183
0
  std::string MaxVersionString;
1184
0
  SmallString<128> Path(IncludePath);
1185
0
  llvm::sys::path::append(Path, "c++");
1186
0
  for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
1187
0
       !EC && LI != LE; LI = LI.increment(EC)) {
1188
0
    StringRef VersionText = llvm::sys::path::filename(LI->path());
1189
0
    int Version;
1190
0
    if (VersionText[0] == 'v' &&
1191
0
        !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
1192
0
      if (Version > MaxVersion) {
1193
0
        MaxVersion = Version;
1194
0
        MaxVersionString = std::string(VersionText);
1195
0
      }
1196
0
    }
1197
0
  }
1198
0
  if (!MaxVersion)
1199
0
    return "";
1200
0
  return MaxVersionString;
1201
0
}
1202
1203
void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1204
0
                                             ArgStringList &CC1Args) const {
1205
  // Header search paths should be handled by each of the subclasses.
1206
  // Historically, they have not been, and instead have been handled inside of
1207
  // the CC1-layer frontend. As the logic is hoisted out, this generic function
1208
  // will slowly stop being called.
1209
  //
1210
  // While it is being called, replicate a bit of a hack to propagate the
1211
  // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
1212
  // header search paths with it. Once all systems are overriding this
1213
  // function, the CC1 flag and this line can be removed.
1214
0
  DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
1215
0
}
1216
1217
void ToolChain::AddClangCXXStdlibIsystemArgs(
1218
    const llvm::opt::ArgList &DriverArgs,
1219
0
    llvm::opt::ArgStringList &CC1Args) const {
1220
0
  DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
1221
  // This intentionally only looks at -nostdinc++, and not -nostdinc or
1222
  // -nostdlibinc. The purpose of -stdlib++-isystem is to support toolchain
1223
  // setups with non-standard search logic for the C++ headers, while still
1224
  // allowing users of the toolchain to bring their own C++ headers. Such a
1225
  // toolchain likely also has non-standard search logic for the C headers and
1226
  // uses -nostdinc to suppress the default logic, but -stdlib++-isystem should
1227
  // still work in that case and only be suppressed by an explicit -nostdinc++
1228
  // in a project using the toolchain.
1229
0
  if (!DriverArgs.hasArg(options::OPT_nostdincxx))
1230
0
    for (const auto &P :
1231
0
         DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
1232
0
      addSystemInclude(DriverArgs, CC1Args, P);
1233
0
}
1234
1235
0
bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
1236
0
  return getDriver().CCCIsCXX() &&
1237
0
         !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
1238
0
                      options::OPT_nostdlibxx);
1239
0
}
1240
1241
void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
1242
0
                                    ArgStringList &CmdArgs) const {
1243
0
  assert(!Args.hasArg(options::OPT_nostdlibxx) &&
1244
0
         "should not have called this");
1245
0
  CXXStdlibType Type = GetCXXStdlibType(Args);
1246
1247
0
  switch (Type) {
1248
0
  case ToolChain::CST_Libcxx:
1249
0
    CmdArgs.push_back("-lc++");
1250
0
    if (Args.hasArg(options::OPT_fexperimental_library))
1251
0
      CmdArgs.push_back("-lc++experimental");
1252
0
    break;
1253
1254
0
  case ToolChain::CST_Libstdcxx:
1255
0
    CmdArgs.push_back("-lstdc++");
1256
0
    break;
1257
0
  }
1258
0
}
1259
1260
void ToolChain::AddFilePathLibArgs(const ArgList &Args,
1261
0
                                   ArgStringList &CmdArgs) const {
1262
0
  for (const auto &LibPath : getFilePaths())
1263
0
    if(LibPath.length() > 0)
1264
0
      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
1265
0
}
1266
1267
void ToolChain::AddCCKextLibArgs(const ArgList &Args,
1268
0
                                 ArgStringList &CmdArgs) const {
1269
0
  CmdArgs.push_back("-lcc_kext");
1270
0
}
1271
1272
bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args,
1273
0
                                           std::string &Path) const {
1274
  // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
1275
  // (to keep the linker options consistent with gcc and clang itself).
1276
0
  if (!isOptimizationLevelFast(Args)) {
1277
    // Check if -ffast-math or -funsafe-math.
1278
0
    Arg *A =
1279
0
      Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
1280
0
                      options::OPT_funsafe_math_optimizations,
1281
0
                      options::OPT_fno_unsafe_math_optimizations);
1282
1283
0
    if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
1284
0
        A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
1285
0
      return false;
1286
0
  }
1287
  // If crtfastmath.o exists add it to the arguments.
1288
0
  Path = GetFilePath("crtfastmath.o");
1289
0
  return (Path != "crtfastmath.o"); // Not found.
1290
0
}
1291
1292
bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args,
1293
0
                                              ArgStringList &CmdArgs) const {
1294
0
  std::string Path;
1295
0
  if (isFastMathRuntimeAvailable(Args, Path)) {
1296
0
    CmdArgs.push_back(Args.MakeArgString(Path));
1297
0
    return true;
1298
0
  }
1299
1300
0
  return false;
1301
0
}
1302
1303
Expected<SmallVector<std::string>>
1304
0
ToolChain::getSystemGPUArchs(const llvm::opt::ArgList &Args) const {
1305
0
  return SmallVector<std::string>();
1306
0
}
1307
1308
0
SanitizerMask ToolChain::getSupportedSanitizers() const {
1309
  // Return sanitizers which don't require runtime support and are not
1310
  // platform dependent.
1311
1312
0
  SanitizerMask Res =
1313
0
      (SanitizerKind::Undefined & ~SanitizerKind::Vptr) |
1314
0
      (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1315
0
      SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
1316
0
      SanitizerKind::KCFI | SanitizerKind::UnsignedIntegerOverflow |
1317
0
      SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
1318
0
      SanitizerKind::Nullability | SanitizerKind::LocalBounds;
1319
0
  if (getTriple().getArch() == llvm::Triple::x86 ||
1320
0
      getTriple().getArch() == llvm::Triple::x86_64 ||
1321
0
      getTriple().getArch() == llvm::Triple::arm || getTriple().isWasm() ||
1322
0
      getTriple().isAArch64() || getTriple().isRISCV() ||
1323
0
      getTriple().isLoongArch64())
1324
0
    Res |= SanitizerKind::CFIICall;
1325
0
  if (getTriple().getArch() == llvm::Triple::x86_64 ||
1326
0
      getTriple().isAArch64(64) || getTriple().isRISCV())
1327
0
    Res |= SanitizerKind::ShadowCallStack;
1328
0
  if (getTriple().isAArch64(64))
1329
0
    Res |= SanitizerKind::MemTag;
1330
0
  return Res;
1331
0
}
1332
1333
void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1334
0
                                   ArgStringList &CC1Args) const {}
1335
1336
void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1337
0
                                  ArgStringList &CC1Args) const {}
1338
1339
llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12>
1340
0
ToolChain::getDeviceLibs(const ArgList &DriverArgs) const {
1341
0
  return {};
1342
0
}
1343
1344
void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
1345
0
                                    ArgStringList &CC1Args) const {}
1346
1347
0
static VersionTuple separateMSVCFullVersion(unsigned Version) {
1348
0
  if (Version < 100)
1349
0
    return VersionTuple(Version);
1350
1351
0
  if (Version < 10000)
1352
0
    return VersionTuple(Version / 100, Version % 100);
1353
1354
0
  unsigned Build = 0, Factor = 1;
1355
0
  for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
1356
0
    Build = Build + (Version % 10) * Factor;
1357
0
  return VersionTuple(Version / 100, Version % 100, Build);
1358
0
}
1359
1360
VersionTuple
1361
ToolChain::computeMSVCVersion(const Driver *D,
1362
0
                              const llvm::opt::ArgList &Args) const {
1363
0
  const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1364
0
  const Arg *MSCompatibilityVersion =
1365
0
      Args.getLastArg(options::OPT_fms_compatibility_version);
1366
1367
0
  if (MSCVersion && MSCompatibilityVersion) {
1368
0
    if (D)
1369
0
      D->Diag(diag::err_drv_argument_not_allowed_with)
1370
0
          << MSCVersion->getAsString(Args)
1371
0
          << MSCompatibilityVersion->getAsString(Args);
1372
0
    return VersionTuple();
1373
0
  }
1374
1375
0
  if (MSCompatibilityVersion) {
1376
0
    VersionTuple MSVT;
1377
0
    if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
1378
0
      if (D)
1379
0
        D->Diag(diag::err_drv_invalid_value)
1380
0
            << MSCompatibilityVersion->getAsString(Args)
1381
0
            << MSCompatibilityVersion->getValue();
1382
0
    } else {
1383
0
      return MSVT;
1384
0
    }
1385
0
  }
1386
1387
0
  if (MSCVersion) {
1388
0
    unsigned Version = 0;
1389
0
    if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1390
0
      if (D)
1391
0
        D->Diag(diag::err_drv_invalid_value)
1392
0
            << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1393
0
    } else {
1394
0
      return separateMSVCFullVersion(Version);
1395
0
    }
1396
0
  }
1397
1398
0
  return VersionTuple();
1399
0
}
1400
1401
llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
1402
    const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1403
0
    SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
1404
0
  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1405
0
  const OptTable &Opts = getDriver().getOpts();
1406
0
  bool Modified = false;
1407
1408
  // Handle -Xopenmp-target flags
1409
0
  for (auto *A : Args) {
1410
    // Exclude flags which may only apply to the host toolchain.
1411
    // Do not exclude flags when the host triple (AuxTriple)
1412
    // matches the current toolchain triple. If it is not present
1413
    // at all, target and host share a toolchain.
1414
0
    if (A->getOption().matches(options::OPT_m_Group)) {
1415
      // Pass code object version to device toolchain
1416
      // to correctly set metadata in intermediate files.
1417
0
      if (SameTripleAsHost ||
1418
0
          A->getOption().matches(options::OPT_mcode_object_version_EQ))
1419
0
        DAL->append(A);
1420
0
      else
1421
0
        Modified = true;
1422
0
      continue;
1423
0
    }
1424
1425
0
    unsigned Index;
1426
0
    unsigned Prev;
1427
0
    bool XOpenMPTargetNoTriple =
1428
0
        A->getOption().matches(options::OPT_Xopenmp_target);
1429
1430
0
    if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1431
0
      llvm::Triple TT(getOpenMPTriple(A->getValue(0)));
1432
1433
      // Passing device args: -Xopenmp-target=<triple> -opt=val.
1434
0
      if (TT.getTriple() == getTripleString())
1435
0
        Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1436
0
      else
1437
0
        continue;
1438
0
    } else if (XOpenMPTargetNoTriple) {
1439
      // Passing device args: -Xopenmp-target -opt=val.
1440
0
      Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1441
0
    } else {
1442
0
      DAL->append(A);
1443
0
      continue;
1444
0
    }
1445
1446
    // Parse the argument to -Xopenmp-target.
1447
0
    Prev = Index;
1448
0
    std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1449
0
    if (!XOpenMPTargetArg || Index > Prev + 1) {
1450
0
      getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
1451
0
          << A->getAsString(Args);
1452
0
      continue;
1453
0
    }
1454
0
    if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
1455
0
        Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
1456
0
      getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1457
0
      continue;
1458
0
    }
1459
0
    XOpenMPTargetArg->setBaseArg(A);
1460
0
    A = XOpenMPTargetArg.release();
1461
0
    AllocatedArgs.push_back(A);
1462
0
    DAL->append(A);
1463
0
    Modified = true;
1464
0
  }
1465
1466
0
  if (Modified)
1467
0
    return DAL;
1468
1469
0
  delete DAL;
1470
0
  return nullptr;
1471
0
}
1472
1473
// TODO: Currently argument values separated by space e.g.
1474
// -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
1475
// fixed.
1476
void ToolChain::TranslateXarchArgs(
1477
    const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
1478
    llvm::opt::DerivedArgList *DAL,
1479
0
    SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1480
0
  const OptTable &Opts = getDriver().getOpts();
1481
0
  unsigned ValuePos = 1;
1482
0
  if (A->getOption().matches(options::OPT_Xarch_device) ||
1483
0
      A->getOption().matches(options::OPT_Xarch_host))
1484
0
    ValuePos = 0;
1485
1486
0
  unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos));
1487
0
  unsigned Prev = Index;
1488
0
  std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(Args, Index));
1489
1490
  // If the argument parsing failed or more than one argument was
1491
  // consumed, the -Xarch_ argument's parameter tried to consume
1492
  // extra arguments. Emit an error and ignore.
1493
  //
1494
  // We also want to disallow any options which would alter the
1495
  // driver behavior; that isn't going to work in our model. We
1496
  // use options::NoXarchOption to control this.
1497
0
  if (!XarchArg || Index > Prev + 1) {
1498
0
    getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1499
0
        << A->getAsString(Args);
1500
0
    return;
1501
0
  } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) {
1502
0
    auto &Diags = getDriver().getDiags();
1503
0
    unsigned DiagID =
1504
0
        Diags.getCustomDiagID(DiagnosticsEngine::Error,
1505
0
                              "invalid Xarch argument: '%0', not all driver "
1506
0
                              "options can be forwared via Xarch argument");
1507
0
    Diags.Report(DiagID) << A->getAsString(Args);
1508
0
    return;
1509
0
  }
1510
0
  XarchArg->setBaseArg(A);
1511
0
  A = XarchArg.release();
1512
0
  if (!AllocatedArgs)
1513
0
    DAL->AddSynthesizedArg(A);
1514
0
  else
1515
0
    AllocatedArgs->push_back(A);
1516
0
}
1517
1518
llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
1519
    const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
1520
    Action::OffloadKind OFK,
1521
0
    SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1522
0
  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1523
0
  bool Modified = false;
1524
1525
0
  bool IsDevice = OFK != Action::OFK_None && OFK != Action::OFK_Host;
1526
0
  for (Arg *A : Args) {
1527
0
    bool NeedTrans = false;
1528
0
    bool Skip = false;
1529
0
    if (A->getOption().matches(options::OPT_Xarch_device)) {
1530
0
      NeedTrans = IsDevice;
1531
0
      Skip = !IsDevice;
1532
0
    } else if (A->getOption().matches(options::OPT_Xarch_host)) {
1533
0
      NeedTrans = !IsDevice;
1534
0
      Skip = IsDevice;
1535
0
    } else if (A->getOption().matches(options::OPT_Xarch__) && IsDevice) {
1536
      // Do not translate -Xarch_ options for non CUDA/HIP toolchain since
1537
      // they may need special translation.
1538
      // Skip this argument unless the architecture matches BoundArch
1539
0
      if (BoundArch.empty() || A->getValue(0) != BoundArch)
1540
0
        Skip = true;
1541
0
      else
1542
0
        NeedTrans = true;
1543
0
    }
1544
0
    if (NeedTrans || Skip)
1545
0
      Modified = true;
1546
0
    if (NeedTrans)
1547
0
      TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
1548
0
    if (!Skip)
1549
0
      DAL->append(A);
1550
0
  }
1551
1552
0
  if (Modified)
1553
0
    return DAL;
1554
1555
0
  delete DAL;
1556
0
  return nullptr;
1557
0
}