Coverage Report

Created: 2023-11-11 10:31

/Users/buildslave/jenkins/workspace/coverage/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
53.0k
static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
60
53.0k
  return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
61
53.0k
                         options::OPT_fno_rtti, options::OPT_frtti);
62
53.0k
}
63
64
static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
65
                                             const llvm::Triple &Triple,
66
53.0k
                                             const Arg *CachedRTTIArg) {
67
  // Explicit rtti/no-rtti args
68
53.0k
  if (CachedRTTIArg) {
69
24.1k
    if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
70
24.0k
      return ToolChain::RM_Enabled;
71
78
    else
72
78
      return ToolChain::RM_Disabled;
73
24.1k
  }
74
75
  // -frtti is default, except for the PS4/PS5 and DriverKit.
76
28.8k
  bool NoRTTI = Triple.isPS() || 
Triple.isDriverKit()28.6k
;
77
28.8k
  return NoRTTI ? 
ToolChain::RM_Disabled311
:
ToolChain::RM_Enabled28.5k
;
78
53.0k
}
79
80
ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
81
                     const ArgList &Args)
82
53.0k
    : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
83
53.0k
      CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
84
106k
  auto addIfExists = [this](path_list &List, const std::string &Path) {
85
106k
    if (getVFS().exists(Path))
86
96
      List.push_back(Path);
87
106k
  };
88
89
53.0k
  if (std::optional<std::string> Path = getRuntimePath())
90
71
    getLibraryPaths().push_back(*Path);
91
53.0k
  if (std::optional<std::string> Path = getStdlibPath())
92
29
    getFilePaths().push_back(*Path);
93
53.0k
  for (const auto &Path : getArchSpecificLibPaths())
94
106k
    addIfExists(getFilePaths(), Path);
95
53.0k
}
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
130
void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
125
130
  Triple.setEnvironment(Env);
126
130
  if (EffectiveTriple != llvm::Triple())
127
0
    EffectiveTriple.setEnvironment(Env);
128
130
}
129
130
53.0k
ToolChain::~ToolChain() = default;
131
132
304k
llvm::vfs::FileSystem &ToolChain::getVFS() const {
133
304k
  return getDriver().getVFS();
134
304k
}
135
136
234k
bool ToolChain::useIntegratedAs() const {
137
234k
  return Args.hasFlag(options::OPT_fintegrated_as,
138
234k
                      options::OPT_fno_integrated_as,
139
234k
                      IsIntegratedAssemblerDefault());
140
234k
}
141
142
47.8k
bool ToolChain::useIntegratedBackend() const {
143
47.8k
  assert(
144
47.8k
      ((IsIntegratedBackendDefault() && IsIntegratedBackendSupported()) ||
145
47.8k
       (!IsIntegratedBackendDefault() || IsNonIntegratedBackendSupported())) &&
146
47.8k
      "(Non-)integrated backend set incorrectly!");
147
148
47.8k
  bool IBackend = Args.hasFlag(options::OPT_fintegrated_objemitter,
149
47.8k
                               options::OPT_fno_integrated_objemitter,
150
47.8k
                               IsIntegratedBackendDefault());
151
152
  // Diagnose when integrated-objemitter options are not supported by this
153
  // toolchain.
154
47.8k
  unsigned DiagID;
155
47.8k
  if ((IBackend && 
!IsIntegratedBackendSupported()47.7k
) ||
156
47.8k
      
(47.8k
!IBackend47.8k
&&
!IsNonIntegratedBackendSupported()22
))
157
1
    DiagID = clang::diag::err_drv_unsupported_opt_for_target;
158
47.8k
  else
159
47.8k
    DiagID = clang::diag::warn_drv_unsupported_opt_for_target;
160
47.8k
  Arg *A = Args.getLastArg(options::OPT_fno_integrated_objemitter);
161
47.8k
  if (A && 
!IsNonIntegratedBackendSupported()2
)
162
1
    D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
163
47.8k
  A = Args.getLastArg(options::OPT_fintegrated_objemitter);
164
47.8k
  if (A && 
!IsIntegratedBackendSupported()2
)
165
0
    D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
166
167
47.8k
  return IBackend;
168
47.8k
}
169
170
11.8k
bool ToolChain::useRelaxRelocations() const {
171
11.8k
  return ENABLE_X86_RELAX_RELOCATIONS;
172
11.8k
}
173
174
601
bool ToolChain::defaultToIEEELongDouble() const {
175
601
  return PPC_LINUX_DEFAULT_IEEELONGDOUBLE && 
getTriple().isOSLinux()0
;
176
601
}
177
178
static void getAArch64MultilibFlags(const Driver &D,
179
                                          const llvm::Triple &Triple,
180
                                          const llvm::opt::ArgList &Args,
181
5
                                          Multilib::flags_list &Result) {
182
5
  std::vector<StringRef> Features;
183
5
  tools::aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, false);
184
5
  const auto UnifiedFeatures = tools::unifyTargetFeatures(Features);
185
5
  llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(),
186
5
                                       UnifiedFeatures.end());
187
5
  std::vector<std::string> MArch;
188
5
  for (const auto &Ext : AArch64::Extensions)
189
470
    if (FeatureSet.contains(Ext.Feature))
190
10
      MArch.push_back(Ext.Name.str());
191
5
  for (const auto &Ext : AArch64::Extensions)
192
470
    if (FeatureSet.contains(Ext.NegFeature))
193
0
      MArch.push_back(("no" + Ext.Name).str());
194
5
  MArch.insert(MArch.begin(), ("-march=" + Triple.getArchName()).str());
195
5
  Result.push_back(llvm::join(MArch, "+"));
196
5
}
197
198
static void getARMMultilibFlags(const Driver &D,
199
                                      const llvm::Triple &Triple,
200
                                      const llvm::opt::ArgList &Args,
201
16
                                      Multilib::flags_list &Result) {
202
16
  std::vector<StringRef> Features;
203
16
  llvm::ARM::FPUKind FPUKind = tools::arm::getARMTargetFeatures(
204
16
      D, Triple, Args, Features, false /*ForAs*/, true /*ForMultilib*/);
205
16
  const auto UnifiedFeatures = tools::unifyTargetFeatures(Features);
206
16
  llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(),
207
16
                                       UnifiedFeatures.end());
208
16
  std::vector<std::string> MArch;
209
16
  for (const auto &Ext : ARM::ARCHExtNames)
210
608
    if (FeatureSet.contains(Ext.Feature))
211
15
      MArch.push_back(Ext.Name.str());
212
16
  for (const auto &Ext : ARM::ARCHExtNames)
213
608
    if (FeatureSet.contains(Ext.NegFeature))
214
95
      MArch.push_back(("no" + Ext.Name).str());
215
16
  MArch.insert(MArch.begin(), ("-march=" + Triple.getArchName()).str());
216
16
  Result.push_back(llvm::join(MArch, "+"));
217
218
16
  switch (FPUKind) {
219
0
#define ARM_FPU(NAME, KIND, VERSION, NEON_SUPPORT, RESTRICTION)                \
220
16
  case llvm::ARM::KIND:                                                        \
221
16
    Result.push_back("-mfpu=" NAME);                                           \
222
16
    break;
223
0
#include "llvm/TargetParser/ARMTargetParser.def"
224
0
  default:
225
0
    llvm_unreachable("Invalid FPUKind");
226
16
  }
227
228
16
  switch (arm::getARMFloatABI(D, Triple, Args)) {
229
2
  case arm::FloatABI::Soft:
230
2
    Result.push_back("-mfloat-abi=soft");
231
2
    break;
232
7
  case arm::FloatABI::SoftFP:
233
7
    Result.push_back("-mfloat-abi=softfp");
234
7
    break;
235
7
  case arm::FloatABI::Hard:
236
7
    Result.push_back("-mfloat-abi=hard");
237
7
    break;
238
0
  case arm::FloatABI::Invalid:
239
0
    llvm_unreachable("Invalid float ABI");
240
16
  }
241
16
}
242
243
Multilib::flags_list
244
21
ToolChain::getMultilibFlags(const llvm::opt::ArgList &Args) const {
245
21
  using namespace clang::driver::options;
246
247
21
  std::vector<std::string> Result;
248
21
  const llvm::Triple Triple(ComputeEffectiveClangTriple(Args));
249
21
  Result.push_back("--target=" + Triple.str());
250
251
21
  switch (Triple.getArch()) {
252
5
  case llvm::Triple::aarch64:
253
5
  case llvm::Triple::aarch64_32:
254
5
  case llvm::Triple::aarch64_be:
255
5
    getAArch64MultilibFlags(D, Triple, Args, Result);
256
5
    break;
257
4
  case llvm::Triple::arm:
258
4
  case llvm::Triple::armeb:
259
16
  case llvm::Triple::thumb:
260
16
  case llvm::Triple::thumbeb:
261
16
    getARMMultilibFlags(D, Triple, Args, Result);
262
16
    break;
263
0
  default:
264
0
    break;
265
21
  }
266
267
  // Sort and remove duplicates.
268
21
  std::sort(Result.begin(), Result.end());
269
21
  Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
270
21
  return Result;
271
21
}
272
273
SanitizerArgs
274
58.6k
ToolChain::getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const {
275
58.6k
  SanitizerArgs SanArgs(*this, JobArgs, !SanitizerArgsChecked);
276
58.6k
  SanitizerArgsChecked = true;
277
58.6k
  return SanArgs;
278
58.6k
}
279
280
53.5k
const XRayArgs& ToolChain::getXRayArgs() const {
281
53.5k
  if (!XRayArguments)
282
50.4k
    XRayArguments.reset(new XRayArgs(*this, Args));
283
53.5k
  return *XRayArguments;
284
53.5k
}
285
286
namespace {
287
288
struct DriverSuffix {
289
  const char *Suffix;
290
  const char *ModeFlag;
291
};
292
293
} // namespace
294
295
214k
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
214k
  static const DriverSuffix DriverSuffixes[] = {
300
214k
      {"clang", nullptr},
301
214k
      {"clang++", "--driver-mode=g++"},
302
214k
      {"clang-c++", "--driver-mode=g++"},
303
214k
      {"clang-cc", nullptr},
304
214k
      {"clang-cpp", "--driver-mode=cpp"},
305
214k
      {"clang-g++", "--driver-mode=g++"},
306
214k
      {"clang-gcc", nullptr},
307
214k
      {"clang-cl", "--driver-mode=cl"},
308
214k
      {"cc", nullptr},
309
214k
      {"cpp", "--driver-mode=cpp"},
310
214k
      {"cl", "--driver-mode=cl"},
311
214k
      {"++", "--driver-mode=g++"},
312
214k
      {"flang", "--driver-mode=flang"},
313
214k
      {"clang-dxc", "--driver-mode=dxc"},
314
214k
  };
315
316
1.42M
  for (const auto &DS : DriverSuffixes) {
317
1.42M
    StringRef Suffix(DS.Suffix);
318
1.42M
    if (ProgName.endswith(Suffix)) {
319
121k
      Pos = ProgName.size() - Suffix.size();
320
121k
      return &DS;
321
121k
    }
322
1.42M
  }
323
93.1k
  return nullptr;
324
214k
}
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
124k
static std::string normalizeProgramName(llvm::StringRef Argv0) {
329
124k
  std::string ProgName = std::string(llvm::sys::path::filename(Argv0));
330
124k
  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
124k
  return ProgName;
336
124k
}
337
338
124k
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
124k
  const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
347
348
124k
  if (!DS && 
ProgName.endswith(".exe")45.0k
) {
349
    // Try again after stripping the executable suffix:
350
    // clang++.exe -> clang++
351
2
    ProgName = ProgName.drop_back(StringRef(".exe").size());
352
2
    DS = FindDriverSuffix(ProgName, Pos);
353
2
  }
354
355
124k
  if (!DS) {
356
    // Try again after stripping any trailing version number:
357
    // clang++3.5 -> clang++
358
45.0k
    ProgName = ProgName.rtrim("0123456789.");
359
45.0k
    DS = FindDriverSuffix(ProgName, Pos);
360
45.0k
  }
361
362
124k
  if (!DS) {
363
    // Try again after stripping trailing -component.
364
    // clang++-tot -> clang++
365
45.0k
    ProgName = ProgName.slice(0, ProgName.rfind('-'));
366
45.0k
    DS = FindDriverSuffix(ProgName, Pos);
367
45.0k
  }
368
124k
  return DS;
369
124k
}
370
371
ParsedClangName
372
124k
ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
373
124k
  std::string ProgName = normalizeProgramName(PN);
374
124k
  size_t SuffixPos;
375
124k
  const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
376
124k
  if (!DS)
377
3.04k
    return {};
378
121k
  size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
379
380
121k
  size_t LastComponent = ProgName.rfind('-', SuffixPos);
381
121k
  if (LastComponent == std::string::npos)
382
121k
    return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
383
95
  std::string ModeSuffix = ProgName.substr(LastComponent + 1,
384
95
                                           SuffixEnd - LastComponent - 1);
385
386
  // Infer target from the prefix.
387
95
  StringRef Prefix(ProgName);
388
95
  Prefix = Prefix.slice(0, LastComponent);
389
95
  std::string IgnoredError;
390
95
  bool IsRegistered =
391
95
      llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError);
392
95
  return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
393
95
                         IsRegistered};
394
121k
}
395
396
29.8k
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
29.8k
  switch (Triple.getArch()) {
401
169
  case llvm::Triple::aarch64: {
402
169
    if (getTriple().isArm64e())
403
12
      return "arm64e";
404
157
    return "arm64";
405
169
  }
406
4
  case llvm::Triple::aarch64_32:
407
4
    return "arm64_32";
408
1
  case llvm::Triple::ppc:
409
1
    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
29.6k
  default:
417
29.6k
    return Triple.getArchName();
418
29.8k
  }
419
29.8k
}
420
421
319
std::string ToolChain::getInputFilename(const InputInfo &Input) const {
422
319
  return Input.getFilename();
423
319
}
424
425
ToolChain::UnwindTableLevel
426
3.46k
ToolChain::getDefaultUnwindTableLevel(const ArgList &Args) const {
427
3.46k
  return UnwindTableLevel::None;
428
3.46k
}
429
430
452
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
452
  return getTriple().isRISCV() ? 
415
:
5437
;
434
452
}
435
436
48.3k
Tool *ToolChain::getClang() const {
437
48.3k
  if (!Clang)
438
47.8k
    Clang.reset(new tools::Clang(*this, useIntegratedBackend()));
439
48.3k
  return Clang.get();
440
48.3k
}
441
442
15
Tool *ToolChain::getFlang() const {
443
15
  if (!Flang)
444
14
    Flang.reset(new tools::Flang(*this));
445
15
  return Flang.get();
446
15
}
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
400
Tool *ToolChain::getAssemble() const {
461
400
  if (!Assemble)
462
398
    Assemble.reset(buildAssembler());
463
400
  return Assemble.get();
464
400
}
465
466
486
Tool *ToolChain::getClangAs() const {
467
486
  if (!Assemble)
468
479
    Assemble.reset(new tools::ClangAs(*this));
469
486
  return Assemble.get();
470
486
}
471
472
7.97k
Tool *ToolChain::getLink() const {
473
7.97k
  if (!Link)
474
7.64k
    Link.reset(buildLinker());
475
7.97k
  return Link.get();
476
7.97k
}
477
478
12
Tool *ToolChain::getStaticLibTool() const {
479
12
  if (!StaticLibTool)
480
12
    StaticLibTool.reset(buildStaticLibTool());
481
12
  return StaticLibTool.get();
482
12
}
483
484
23
Tool *ToolChain::getIfsMerge() const {
485
23
  if (!IfsMerge)
486
21
    IfsMerge.reset(new tools::ifstool::Merger(*this));
487
23
  return IfsMerge.get();
488
23
}
489
490
76
Tool *ToolChain::getOffloadBundler() const {
491
76
  if (!OffloadBundler)
492
55
    OffloadBundler.reset(new tools::OffloadBundler(*this));
493
76
  return OffloadBundler.get();
494
76
}
495
496
13
Tool *ToolChain::getOffloadPackager() const {
497
13
  if (!OffloadPackager)
498
13
    OffloadPackager.reset(new tools::OffloadPackager(*this));
499
13
  return OffloadPackager.get();
500
13
}
501
502
11
Tool *ToolChain::getLinkerWrapper() const {
503
11
  if (!LinkerWrapper)
504
11
    LinkerWrapper.reset(new tools::LinkerWrapper(*this, getLink()));
505
11
  return LinkerWrapper.get();
506
11
}
507
508
8.60k
Tool *ToolChain::getTool(Action::ActionClass AC) const {
509
8.60k
  switch (AC) {
510
400
  case Action::AssembleJobClass:
511
400
    return getAssemble();
512
513
23
  case Action::IfsMergeJobClass:
514
23
    return getIfsMerge();
515
516
7.96k
  case Action::LinkJobClass:
517
7.96k
    return getLink();
518
519
12
  case Action::StaticLibJobClass:
520
12
    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
44
  case Action::CompileJobClass:
532
44
  case Action::PrecompileJobClass:
533
45
  case Action::PreprocessJobClass:
534
48
  case Action::ExtractAPIJobClass:
535
104
  case Action::AnalyzeJobClass:
536
104
  case Action::MigrateJobClass:
537
106
  case Action::VerifyPCHJobClass:
538
106
  case Action::BackendJobClass:
539
106
    return getClang();
540
541
36
  case Action::OffloadBundlingJobClass:
542
76
  case Action::OffloadUnbundlingJobClass:
543
76
    return getOffloadBundler();
544
545
13
  case Action::OffloadPackagerJobClass:
546
13
    return getOffloadPackager();
547
11
  case Action::LinkerWrapperJobClass:
548
11
    return getLinkerWrapper();
549
8.60k
  }
550
551
0
  llvm_unreachable("Invalid tool kind.");
552
0
}
553
554
static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
555
2.32k
                                             const ArgList &Args) {
556
2.32k
  const llvm::Triple &Triple = TC.getTriple();
557
2.32k
  bool IsWindows = Triple.isOSWindows();
558
559
2.32k
  if (TC.isBareMetal())
560
706
    return Triple.getArchName();
561
562
1.62k
  if (TC.getArch() == llvm::Triple::arm || 
TC.getArch() == llvm::Triple::armeb1.43k
)
563
192
    return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && 
!IsWindows24
)
564
192
               ? 
"armhf"12
565
192
               : 
"arm"180
;
566
567
  // For historic reasons, Android library is using i686 instead of i386.
568
1.42k
  if (TC.getArch() == llvm::Triple::x86 && 
Triple.isAndroid()175
)
569
25
    return "i686";
570
571
1.40k
  if (TC.getArch() == llvm::Triple::x86_64 && 
Triple.isX32()845
)
572
6
    return "x32";
573
574
1.39k
  return llvm::Triple::getArchTypeName(TC.getArch());
575
1.40k
}
576
577
64.8k
StringRef ToolChain::getOSLibName() const {
578
64.8k
  if (Triple.isOSDarwin())
579
22.2k
    return "darwin";
580
581
42.5k
  switch (Triple.getOS()) {
582
582
  case llvm::Triple::FreeBSD:
583
582
    return "freebsd";
584
977
  case llvm::Triple::NetBSD:
585
977
    return "netbsd";
586
276
  case llvm::Triple::OpenBSD:
587
276
    return "openbsd";
588
577
  case llvm::Triple::Solaris:
589
577
    return "sunos";
590
618
  case llvm::Triple::AIX:
591
618
    return "aix";
592
39.5k
  default:
593
39.5k
    return getOS();
594
42.5k
  }
595
42.5k
}
596
597
12.8k
std::string ToolChain::getCompilerRTPath() const {
598
12.8k
  SmallString<128> Path(getDriver().ResourceDir);
599
12.8k
  if (isBareMetal()) {
600
706
    llvm::sys::path::append(Path, "lib", getOSLibName());
601
706
    if (!SelectedMultilibs.empty()) {
602
73
      Path += SelectedMultilibs.back().gccSuffix();
603
73
    }
604
12.1k
  } else if (Triple.isOSUnknown()) {
605
365
    llvm::sys::path::append(Path, "lib");
606
11.8k
  } else {
607
11.8k
    llvm::sys::path::append(Path, "lib", getOSLibName());
608
11.8k
  }
609
12.8k
  return std::string(Path.str());
610
12.8k
}
611
612
std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
613
                                             StringRef Component,
614
28
                                             FileType Type) const {
615
28
  std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type);
616
28
  return llvm::sys::path::filename(CRTAbsolutePath).str();
617
28
}
618
619
std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args,
620
                                               StringRef Component,
621
                                               FileType Type,
622
4.72k
                                               bool AddArch) const {
623
4.72k
  const llvm::Triple &TT = getTriple();
624
4.72k
  bool IsITANMSVCWindows =
625
4.72k
      TT.isWindowsMSVCEnvironment() || 
TT.isWindowsItaniumEnvironment()4.51k
;
626
627
4.72k
  const char *Prefix =
628
4.72k
      IsITANMSVCWindows || 
Type == ToolChain::FT_Object4.48k
?
""320
:
"lib"4.40k
;
629
4.72k
  const char *Suffix;
630
4.72k
  switch (Type) {
631
80
  case ToolChain::FT_Object:
632
80
    Suffix = IsITANMSVCWindows ? 
".obj"0
: ".o";
633
80
    break;
634
4.55k
  case ToolChain::FT_Static:
635
4.55k
    Suffix = IsITANMSVCWindows ? 
".lib"240
:
".a"4.31k
;
636
4.55k
    break;
637
91
  case ToolChain::FT_Shared:
638
91
    Suffix = TT.isOSWindows()
639
91
                 ? 
(8
TT.isWindowsGNUEnvironment()8
?
".dll.a"8
:
".lib"0
)
640
91
                 : 
".so"83
;
641
91
    break;
642
4.72k
  }
643
644
4.72k
  std::string ArchAndEnv;
645
4.72k
  if (AddArch) {
646
2.32k
    StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
647
2.32k
    const char *Env = TT.isAndroid() ? 
"-android"308
:
""2.01k
;
648
2.32k
    ArchAndEnv = ("-" + Arch + Env).str();
649
2.32k
  }
650
4.72k
  return (Prefix + Twine("clang_rt.") + Component + ArchAndEnv + Suffix).str();
651
4.72k
}
652
653
std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
654
2.39k
                                     FileType Type) const {
655
  // Check for runtime files in the new layout without the architecture first.
656
2.39k
  std::string CRTBasename =
657
2.39k
      buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/false);
658
2.39k
  for (const auto &LibPath : getLibraryPaths()) {
659
928
    SmallString<128> P(LibPath);
660
928
    llvm::sys::path::append(P, CRTBasename);
661
928
    if (getVFS().exists(P))
662
67
      return std::string(P.str());
663
928
  }
664
665
  // Fall back to the old expected compiler-rt name if the new one does not
666
  // exist.
667
2.32k
  CRTBasename =
668
2.32k
      buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/true);
669
2.32k
  SmallString<128> Path(getCompilerRTPath());
670
2.32k
  llvm::sys::path::append(Path, CRTBasename);
671
2.32k
  return std::string(Path.str());
672
2.39k
}
673
674
const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
675
                                              StringRef Component,
676
1.32k
                                              FileType Type) const {
677
1.32k
  return Args.MakeArgString(getCompilerRT(Args, Component, Type));
678
1.32k
}
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
487
ToolChain::getFallbackAndroidTargetPath(StringRef BaseDir) const {
685
487
  llvm::Triple TripleWithoutLevel(getTriple());
686
487
  TripleWithoutLevel.setEnvironmentName("android"); // remove any version number
687
487
  const std::string &TripleWithoutLevelStr = TripleWithoutLevel.str();
688
487
  unsigned TripleVersion = getTriple().getEnvironmentVersion().getMajor();
689
487
  unsigned BestVersion = 0;
690
691
487
  SmallString<32> TripleDir;
692
487
  bool UsingUnversionedDir = false;
693
487
  std::error_code EC;
694
487
  for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(BaseDir, EC), LE;
695
75.7k
       !EC && 
LI != LE75.5k
;
LI = LI.increment(EC)75.2k
) {
696
75.2k
    StringRef DirName = llvm::sys::path::filename(LI->path());
697
75.2k
    StringRef DirNameSuffix = DirName;
698
75.2k
    if (DirNameSuffix.consume_front(TripleWithoutLevelStr)) {
699
34
      if (DirNameSuffix.empty() && 
TripleDir.empty()14
) {
700
10
        TripleDir = DirName;
701
10
        UsingUnversionedDir = true;
702
24
      } else {
703
24
        unsigned Version;
704
24
        if (!DirNameSuffix.getAsInteger(10, Version) && 
Version > BestVersion20
&&
705
24
            
Version < TripleVersion18
) {
706
8
          BestVersion = Version;
707
8
          TripleDir = DirName;
708
8
          UsingUnversionedDir = false;
709
8
        }
710
24
      }
711
34
    }
712
75.2k
  }
713
714
487
  if (TripleDir.empty())
715
473
    return {};
716
717
14
  SmallString<128> P(BaseDir);
718
14
  llvm::sys::path::append(P, TripleDir);
719
14
  if (UsingUnversionedDir)
720
6
    D.Diag(diag::warn_android_unversioned_fallback) << P << getTripleString();
721
14
  return std::string(P);
722
487
}
723
724
std::optional<std::string>
725
106k
ToolChain::getTargetSubDirPath(StringRef BaseDir) const {
726
106k
  auto getPathForTriple =
727
110k
      [&](const llvm::Triple &Triple) -> std::optional<std::string> {
728
110k
    SmallString<128> P(BaseDir);
729
110k
    llvm::sys::path::append(P, Triple.str());
730
110k
    if (getVFS().exists(P))
731
218
      return std::string(P);
732
110k
    return {};
733
110k
  };
734
735
106k
  if (auto Path = getPathForTriple(getTriple()))
736
214
    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
106k
  if (getTriple().getArch() == Triple::arm && 
!getTriple().isArmMClass()4.07k
) {
754
3.94k
    llvm::Triple ArmTriple = getTriple();
755
3.94k
    ArmTriple.setArch(Triple::arm);
756
3.94k
    if (auto Path = getPathForTriple(ArmTriple))
757
4
      return *Path;
758
3.94k
  }
759
760
106k
  if (getTriple().isAndroid())
761
487
    return getFallbackAndroidTargetPath(BaseDir);
762
763
105k
  return {};
764
106k
}
765
766
53.0k
std::optional<std::string> ToolChain::getRuntimePath() const {
767
53.0k
  SmallString<128> P(D.ResourceDir);
768
53.0k
  llvm::sys::path::append(P, "lib");
769
53.0k
  return getTargetSubDirPath(P);
770
53.0k
}
771
772
53.5k
std::optional<std::string> ToolChain::getStdlibPath() const {
773
53.5k
  SmallString<128> P(D.Dir);
774
53.5k
  llvm::sys::path::append(P, "..", "lib");
775
53.5k
  return getTargetSubDirPath(P);
776
53.5k
}
777
778
53.0k
ToolChain::path_list ToolChain::getArchSpecificLibPaths() const {
779
53.0k
  path_list Paths;
780
781
106k
  auto AddPath = [&](const ArrayRef<StringRef> &SS) {
782
106k
    SmallString<128> Path(getDriver().ResourceDir);
783
106k
    llvm::sys::path::append(Path, "lib");
784
106k
    for (auto &S : SS)
785
159k
      llvm::sys::path::append(Path, S);
786
106k
    Paths.push_back(std::string(Path.str()));
787
106k
  };
788
789
53.0k
  AddPath({getTriple().str()});
790
53.0k
  AddPath({getOSLibName(), llvm::Triple::getArchTypeName(getArch())});
791
53.0k
  return Paths;
792
53.0k
}
793
794
7.73k
bool ToolChain::needsProfileRT(const ArgList &Args) {
795
7.73k
  if (Args.hasArg(options::OPT_noprofilelib))
796
4
    return false;
797
798
7.72k
  return Args.hasArg(options::OPT_fprofile_generate) ||
799
7.72k
         
Args.hasArg(options::OPT_fprofile_generate_EQ)7.71k
||
800
7.72k
         
Args.hasArg(options::OPT_fcs_profile_generate)7.71k
||
801
7.72k
         
Args.hasArg(options::OPT_fcs_profile_generate_EQ)7.71k
||
802
7.72k
         
Args.hasArg(options::OPT_fprofile_instr_generate)7.70k
||
803
7.72k
         
Args.hasArg(options::OPT_fprofile_instr_generate_EQ)7.66k
||
804
7.72k
         
Args.hasArg(options::OPT_fcreate_profile)7.66k
||
805
7.72k
         
Args.hasArg(options::OPT_forder_file_instrumentation)7.66k
;
806
7.73k
}
807
808
53.5k
bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
809
53.5k
  return Args.hasArg(options::OPT_coverage) ||
810
53.5k
         Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
811
53.4k
                      false);
812
53.5k
}
813
814
57.4k
Tool *ToolChain::SelectTool(const JobAction &JA) const {
815
57.4k
  if (D.IsFlangMode() && 
getDriver().ShouldUseFlangCompiler(JA)20
)
return getFlang()15
;
816
57.4k
  if (getDriver().ShouldUseClangCompiler(JA)) 
return getClang()48.2k
;
817
9.14k
  Action::ActionClass AC = JA.getKind();
818
9.14k
  if (AC == Action::AssembleJobClass && 
useIntegratedAs()886
&&
819
9.14k
      
!getTriple().isOSAIX()491
)
820
486
    return getClangAs();
821
8.66k
  return getTool(AC);
822
9.14k
}
823
824
10.1k
std::string ToolChain::GetFilePath(const char *Name) const {
825
10.1k
  return D.GetFilePath(Name, *this);
826
10.1k
}
827
828
9.06k
std::string ToolChain::GetProgramPath(const char *Name) const {
829
9.06k
  return D.GetProgramPath(Name, *this);
830
9.06k
}
831
832
6.47k
std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD) const {
833
6.47k
  if (LinkerIsLLD)
834
3.38k
    *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
6.47k
  const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
839
6.47k
  StringRef UseLinker = A ? 
A->getValue()486
:
CLANG_DEFAULT_LINKER5.99k
;
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
6.47k
  if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
847
12
    std::string Path(A->getValue());
848
12
    if (!Path.empty()) {
849
11
      if (llvm::sys::path::parent_path(Path).empty())
850
5
        Path = GetProgramPath(A->getValue());
851
11
      if (llvm::sys::fs::can_execute(Path)) {
852
9
        if (LinkerIsLLD)
853
1
          *LinkerIsLLD = UseLinker == "lld";
854
9
        return std::string(Path);
855
9
      }
856
11
    }
857
3
    getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
858
3
    return GetProgramPath(getDefaultLinker());
859
12
  }
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
6.46k
  if (UseLinker.empty() || 
UseLinker == "ld"376
) {
863
6.35k
    const char *DefaultLinker = getDefaultLinker();
864
6.35k
    if (llvm::sys::path::is_absolute(DefaultLinker))
865
6
      return std::string(DefaultLinker);
866
6.34k
    else
867
6.34k
      return GetProgramPath(DefaultLinker);
868
6.35k
  }
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
116
  if (UseLinker.contains('/'))
875
5
    getDriver().Diag(diag::warn_drv_fuse_ld_path);
876
877
116
  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
5
    if (llvm::sys::fs::can_execute(UseLinker))
881
2
      return std::string(UseLinker);
882
111
  } else {
883
111
    llvm::SmallString<8> LinkerName;
884
111
    if (Triple.isOSDarwin())
885
14
      LinkerName.append("ld64.");
886
97
    else
887
97
      LinkerName.append("ld.");
888
111
    LinkerName.append(UseLinker);
889
890
111
    std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
891
111
    if (llvm::sys::fs::can_execute(LinkerPath)) {
892
107
      if (LinkerIsLLD)
893
14
        *LinkerIsLLD = UseLinker == "lld";
894
107
      return LinkerPath;
895
107
    }
896
111
  }
897
898
7
  if (A)
899
7
    getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
900
901
7
  return GetProgramPath(getDefaultLinker());
902
116
}
903
904
8
std::string ToolChain::GetStaticLibToolPath() const {
905
  // TODO: Add support for static lib archiving on Windows
906
8
  if (Triple.isOSDarwin())
907
2
    return GetProgramPath("libtool");
908
6
  return GetProgramPath("llvm-ar");
909
8
}
910
911
45.8k
types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
912
45.8k
  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
45.8k
  if (D.IsFlangMode() && 
id == types::TY_PP_Fortran16
)
918
9
    id = types::TY_Fortran;
919
920
45.8k
  return id;
921
45.8k
}
922
923
396
bool ToolChain::HasNativeLLVMSupport() const {
924
396
  return false;
925
396
}
926
927
2.66k
bool ToolChain::isCrossCompiling() const {
928
2.66k
  llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
929
2.66k
  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
2.66k
  default:
939
2.66k
    return HostTriple.getArch() != getArch();
940
2.66k
  }
941
2.66k
}
942
943
30.2k
ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
944
30.2k
  return ObjCRuntime(isNonFragile ? 
ObjCRuntime::GNUstep1.68k
:
ObjCRuntime::GCC28.5k
,
945
30.2k
                     VersionTuple());
946
30.2k
}
947
948
llvm::ExceptionHandling
949
29.8k
ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
950
29.8k
  return llvm::ExceptionHandling::None;
951
29.8k
}
952
953
14
bool ToolChain::isThreadModelSupported(const StringRef Model) const {
954
14
  if (Model == "single") {
955
    // FIXME: 'single' is only supported on ARM and WebAssembly so far.
956
5
    return Triple.getArch() == llvm::Triple::arm ||
957
5
           
Triple.getArch() == llvm::Triple::armeb2
||
958
5
           
Triple.getArch() == llvm::Triple::thumb2
||
959
5
           
Triple.getArch() == llvm::Triple::thumbeb2
||
Triple.isWasm()2
;
960
9
  } else if (Model == "posix")
961
5
    return true;
962
963
4
  return false;
964
14
}
965
966
std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
967
57.8k
                                         types::ID InputType) const {
968
57.8k
  switch (getTriple().getArch()) {
969
18.0k
  default:
970
18.0k
    return getTripleString();
971
972
34.4k
  case llvm::Triple::x86_64: {
973
34.4k
    llvm::Triple Triple = getTriple();
974
34.4k
    if (!Triple.isOSBinFormatMachO())
975
13.4k
      return getTripleString();
976
977
21.0k
    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
2
      StringRef MArch = A->getValue();
981
2
      if (MArch == "x86_64h")
982
0
        Triple.setArchName(MArch);
983
2
    }
984
21.0k
    return Triple.getTriple();
985
34.4k
  }
986
2.07k
  case llvm::Triple::aarch64: {
987
2.07k
    llvm::Triple Triple = getTriple();
988
2.07k
    if (!Triple.isOSBinFormatMachO())
989
1.78k
      return getTripleString();
990
991
290
    if (Triple.isArm64e())
992
19
      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
271
    Triple.setArchName("arm64");
998
271
    return Triple.getTriple();
999
290
  }
1000
12
  case llvm::Triple::aarch64_32:
1001
12
    return getTripleString();
1002
2.88k
  case llvm::Triple::arm:
1003
3.07k
  case llvm::Triple::armeb:
1004
3.18k
  case llvm::Triple::thumb:
1005
3.21k
  case llvm::Triple::thumbeb: {
1006
3.21k
    llvm::Triple Triple = getTriple();
1007
3.21k
    tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple);
1008
3.21k
    tools::arm::setFloatABIInTriple(getDriver(), Args, Triple);
1009
3.21k
    return Triple.getTriple();
1010
3.18k
  }
1011
57.8k
  }
1012
57.8k
}
1013
1014
std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
1015
35.6k
                                                   types::ID InputType) const {
1016
35.6k
  return ComputeLLVMTriple(Args, InputType);
1017
35.6k
}
1018
1019
46
std::string ToolChain::computeSysRoot() const {
1020
46
  return D.SysRoot;
1021
46
}
1022
1023
void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1024
13.1k
                                          ArgStringList &CC1Args) const {
1025
  // Each toolchain should provide the appropriate include flags.
1026
13.1k
}
1027
1028
void ToolChain::addClangTargetOptions(
1029
    const ArgList &DriverArgs, ArgStringList &CC1Args,
1030
188
    Action::OffloadKind DeviceOffloadKind) const {}
1031
1032
void ToolChain::addClangCC1ASTargetOptions(const ArgList &Args,
1033
410
                                           ArgStringList &CC1ASArgs) const {}
1034
1035
30.1k
void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
1036
1037
void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
1038
2.65k
                                 llvm::opt::ArgStringList &CmdArgs) const {
1039
2.65k
  if (!needsProfileRT(Args) && 
!needsGCovInstrumentation(Args)2.61k
)
1040
2.60k
    return;
1041
1042
45
  CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
1043
45
}
1044
1045
ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
1046
11.2k
    const ArgList &Args) const {
1047
11.2k
  if (runtimeLibType)
1048
7.09k
    return *runtimeLibType;
1049
1050
4.12k
  const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
1051
4.12k
  StringRef LibName = A ? 
A->getValue()281
:
CLANG_DEFAULT_RTLIB3.84k
;
1052
1053
  // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
1054
4.12k
  if (LibName == "compiler-rt")
1055
60
    runtimeLibType = ToolChain::RLT_CompilerRT;
1056
4.06k
  else if (LibName == "libgcc")
1057
51
    runtimeLibType = ToolChain::RLT_Libgcc;
1058
4.01k
  else if (LibName == "platform")
1059
168
    runtimeLibType = GetDefaultRuntimeLibType();
1060
3.84k
  else {
1061
3.84k
    if (A)
1062
2
      getDriver().Diag(diag::err_drv_invalid_rtlib_name)
1063
2
          << A->getAsString(Args);
1064
1065
3.84k
    runtimeLibType = GetDefaultRuntimeLibType();
1066
3.84k
  }
1067
1068
4.12k
  return *runtimeLibType;
1069
11.2k
}
1070
1071
ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
1072
3.30k
    const ArgList &Args) const {
1073
3.30k
  if (unwindLibType)
1074
1.49k
    return *unwindLibType;
1075
1076
1.80k
  const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
1077
1.80k
  StringRef LibName = A ? 
A->getValue()184
:
CLANG_DEFAULT_UNWINDLIB1.62k
;
1078
1079
1.80k
  if (LibName == "none")
1080
0
    unwindLibType = ToolChain::UNW_None;
1081
1.80k
  else if (LibName == "platform" || 
LibName == ""1.67k
) {
1082
1.76k
    ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
1083
1.76k
    if (RtLibType == ToolChain::RLT_CompilerRT) {
1084
382
      if (getTriple().isAndroid() || 
getTriple().isOSAIX()240
)
1085
240
        unwindLibType = ToolChain::UNW_CompilerRT;
1086
142
      else
1087
142
        unwindLibType = ToolChain::UNW_None;
1088
1.38k
    } else if (RtLibType == ToolChain::RLT_Libgcc)
1089
1.38k
      unwindLibType = ToolChain::UNW_Libgcc;
1090
1.76k
  } else 
if (47
LibName == "libunwind"47
) {
1091
40
    if (GetRuntimeLibType(Args) == RLT_Libgcc)
1092
5
      getDriver().Diag(diag::err_drv_incompatible_unwindlib);
1093
40
    unwindLibType = ToolChain::UNW_CompilerRT;
1094
40
  } else 
if (7
LibName == "libgcc"7
)
1095
6
    unwindLibType = ToolChain::UNW_Libgcc;
1096
1
  else {
1097
1
    if (A)
1098
1
      getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
1099
1
          << A->getAsString(Args);
1100
1101
1
    unwindLibType = GetDefaultUnwindLibType();
1102
1
  }
1103
1104
1.80k
  return *unwindLibType;
1105
3.30k
}
1106
1107
27.4k
ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
1108
27.4k
  if (cxxStdlibType)
1109
2.57k
    return *cxxStdlibType;
1110
1111
24.8k
  const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
1112
24.8k
  StringRef LibName = A ? 
A->getValue()209
:
CLANG_DEFAULT_CXX_STDLIB24.6k
;
1113
1114
  // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
1115
24.8k
  if (LibName == "libc++")
1116
62
    cxxStdlibType = ToolChain::CST_Libcxx;
1117
24.8k
  else if (LibName == "libstdc++")
1118
81
    cxxStdlibType = ToolChain::CST_Libstdcxx;
1119
24.7k
  else if (LibName == "platform")
1120
65
    cxxStdlibType = GetDefaultCXXStdlibType();
1121
24.6k
  else {
1122
24.6k
    if (A)
1123
1
      getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1124
1
          << A->getAsString(Args);
1125
1126
24.6k
    cxxStdlibType = GetDefaultCXXStdlibType();
1127
24.6k
  }
1128
1129
24.8k
  return *cxxStdlibType;
1130
27.4k
}
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
66.8k
                                            const Twine &Path) {
1136
66.8k
  CC1Args.push_back("-internal-isystem");
1137
66.8k
  CC1Args.push_back(DriverArgs.MakeArgString(Path));
1138
66.8k
}
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
31.2k
                                                   const Twine &Path) {
1151
31.2k
  CC1Args.push_back("-internal-externc-isystem");
1152
31.2k
  CC1Args.push_back(DriverArgs.MakeArgString(Path));
1153
31.2k
}
1154
1155
void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
1156
                                                ArgStringList &CC1Args,
1157
18
                                                const Twine &Path) {
1158
18
  if (llvm::sys::fs::exists(Path))
1159
16
    addExternCSystemInclude(DriverArgs, CC1Args, Path);
1160
18
}
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
6
                                             ArrayRef<StringRef> Paths) {
1166
7
  for (const auto &Path : Paths) {
1167
7
    CC1Args.push_back("-internal-isystem");
1168
7
    CC1Args.push_back(DriverArgs.MakeArgString(Path));
1169
7
  }
1170
6
}
1171
1172
/*static*/ std::string ToolChain::concat(StringRef Path, const Twine &A,
1173
                                         const Twine &B, const Twine &C,
1174
86.1k
                                         const Twine &D) {
1175
86.1k
  SmallString<128> Result(Path);
1176
86.1k
  llvm::sys::path::append(Result, llvm::sys::path::Style::posix, A, B, C, D);
1177
86.1k
  return std::string(Result);
1178
86.1k
}
1179
1180
166
std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const {
1181
166
  std::error_code EC;
1182
166
  int MaxVersion = 0;
1183
166
  std::string MaxVersionString;
1184
166
  SmallString<128> Path(IncludePath);
1185
166
  llvm::sys::path::append(Path, "c++");
1186
166
  for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
1187
257
       !EC && 
LI != LE178
;
LI = LI.increment(EC)91
) {
1188
91
    StringRef VersionText = llvm::sys::path::filename(LI->path());
1189
91
    int Version;
1190
91
    if (VersionText[0] == 'v' &&
1191
91
        
!VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)90
) {
1192
90
      if (Version > MaxVersion) {
1193
90
        MaxVersion = Version;
1194
90
        MaxVersionString = std::string(VersionText);
1195
90
      }
1196
90
    }
1197
91
  }
1198
166
  if (!MaxVersion)
1199
79
    return "";
1200
87
  return MaxVersionString;
1201
166
}
1202
1203
void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1204
13.4k
                                             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
13.4k
  DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
1215
13.4k
}
1216
1217
void ToolChain::AddClangCXXStdlibIsystemArgs(
1218
    const llvm::opt::ArgList &DriverArgs,
1219
10
    llvm::opt::ArgStringList &CC1Args) const {
1220
10
  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
10
  if (!DriverArgs.hasArg(options::OPT_nostdincxx))
1230
8
    for (const auto &P :
1231
8
         DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
1232
14
      addSystemInclude(DriverArgs, CC1Args, P);
1233
10
}
1234
1235
4.15k
bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
1236
4.15k
  return getDriver().CCCIsCXX() &&
1237
4.15k
         !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
1238
2.74k
                      options::OPT_nostdlibxx);
1239
4.15k
}
1240
1241
void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
1242
91
                                    ArgStringList &CmdArgs) const {
1243
91
  assert(!Args.hasArg(options::OPT_nostdlibxx) &&
1244
91
         "should not have called this");
1245
91
  CXXStdlibType Type = GetCXXStdlibType(Args);
1246
1247
91
  switch (Type) {
1248
38
  case ToolChain::CST_Libcxx:
1249
38
    CmdArgs.push_back("-lc++");
1250
38
    if (Args.hasArg(options::OPT_fexperimental_library))
1251
0
      CmdArgs.push_back("-lc++experimental");
1252
38
    break;
1253
1254
53
  case ToolChain::CST_Libstdcxx:
1255
53
    CmdArgs.push_back("-lstdc++");
1256
53
    break;
1257
91
  }
1258
91
}
1259
1260
void ToolChain::AddFilePathLibArgs(const ArgList &Args,
1261
2.67k
                                   ArgStringList &CmdArgs) const {
1262
2.67k
  for (const auto &LibPath : getFilePaths())
1263
4.07k
    if(LibPath.length() > 0)
1264
4.01k
      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
1265
2.67k
}
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
7.31k
                                           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
7.31k
  if (!isOptimizationLevelFast(Args)) {
1277
    // Check if -ffast-math or -funsafe-math.
1278
7.28k
    Arg *A =
1279
7.28k
      Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
1280
7.28k
                      options::OPT_funsafe_math_optimizations,
1281
7.28k
                      options::OPT_fno_unsafe_math_optimizations);
1282
1283
7.28k
    if (!A || 
A->getOption().getID() == options::OPT_fno_fast_math33
||
1284
7.28k
        
A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations26
)
1285
7.26k
      return false;
1286
7.28k
  }
1287
  // If crtfastmath.o exists add it to the arguments.
1288
50
  Path = GetFilePath("crtfastmath.o");
1289
50
  return (Path != "crtfastmath.o"); // Not found.
1290
7.31k
}
1291
1292
bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args,
1293
1.68k
                                              ArgStringList &CmdArgs) const {
1294
1.68k
  std::string Path;
1295
1.68k
  if (isFastMathRuntimeAvailable(Args, Path)) {
1296
13
    CmdArgs.push_back(Args.MakeArgString(Path));
1297
13
    return true;
1298
13
  }
1299
1300
1.67k
  return false;
1301
1.68k
}
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
58.6k
SanitizerMask ToolChain::getSupportedSanitizers() const {
1309
  // Return sanitizers which don't require runtime support and are not
1310
  // platform dependent.
1311
1312
58.6k
  SanitizerMask Res =
1313
58.6k
      (SanitizerKind::Undefined & ~SanitizerKind::Vptr) |
1314
58.6k
      (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1315
58.6k
      SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
1316
58.6k
      SanitizerKind::KCFI | SanitizerKind::UnsignedIntegerOverflow |
1317
58.6k
      SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
1318
58.6k
      SanitizerKind::Nullability | SanitizerKind::LocalBounds;
1319
58.6k
  if (getTriple().getArch() == llvm::Triple::x86 ||
1320
58.6k
      
getTriple().getArch() == llvm::Triple::x86_6446.5k
||
1321
58.6k
      
getTriple().getArch() == llvm::Triple::arm9.71k
||
getTriple().isWasm()7.16k
||
1322
58.6k
      
getTriple().isAArch64()7.03k
||
getTriple().isRISCV()4.60k
||
1323
58.6k
      
getTriple().isLoongArch64()3.72k
)
1324
55.0k
    Res |= SanitizerKind::CFIICall;
1325
58.6k
  if (getTriple().getArch() == llvm::Triple::x86_64 ||
1326
58.6k
      
getTriple().isAArch64(64)21.7k
||
getTriple().isRISCV()19.3k
)
1327
40.1k
    Res |= SanitizerKind::ShadowCallStack;
1328
58.6k
  if (getTriple().isAArch64(64))
1329
2.41k
    Res |= SanitizerKind::MemTag;
1330
58.6k
  return Res;
1331
58.6k
}
1332
1333
void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1334
5
                                   ArgStringList &CC1Args) const {}
1335
1336
void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1337
1
                                  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
38
static VersionTuple separateMSVCFullVersion(unsigned Version) {
1348
38
  if (Version < 100)
1349
2
    return VersionTuple(Version);
1350
1351
36
  if (Version < 10000)
1352
34
    return VersionTuple(Version / 100, Version % 100);
1353
1354
2
  unsigned Build = 0, Factor = 1;
1355
12
  for (; Version > 10000; 
Version = Version / 10, Factor = Factor * 1010
)
1356
10
    Build = Build + (Version % 10) * Factor;
1357
2
  return VersionTuple(Version / 100, Version % 100, Build);
1358
36
}
1359
1360
VersionTuple
1361
ToolChain::computeMSVCVersion(const Driver *D,
1362
57.3k
                              const llvm::opt::ArgList &Args) const {
1363
57.3k
  const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1364
57.3k
  const Arg *MSCompatibilityVersion =
1365
57.3k
      Args.getLastArg(options::OPT_fms_compatibility_version);
1366
1367
57.3k
  if (MSCVersion && 
MSCompatibilityVersion40
) {
1368
2
    if (D)
1369
1
      D->Diag(diag::err_drv_argument_not_allowed_with)
1370
1
          << MSCVersion->getAsString(Args)
1371
1
          << MSCompatibilityVersion->getAsString(Args);
1372
2
    return VersionTuple();
1373
2
  }
1374
1375
57.3k
  if (MSCompatibilityVersion) {
1376
21
    VersionTuple MSVT;
1377
21
    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
21
    } else {
1383
21
      return MSVT;
1384
21
    }
1385
21
  }
1386
1387
57.3k
  if (MSCVersion) {
1388
38
    unsigned Version = 0;
1389
38
    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
38
    } else {
1394
38
      return separateMSVCFullVersion(Version);
1395
38
    }
1396
38
  }
1397
1398
57.2k
  return VersionTuple();
1399
57.3k
}
1400
1401
llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
1402
    const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1403
25
    SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
1404
25
  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1405
25
  const OptTable &Opts = getDriver().getOpts();
1406
25
  bool Modified = false;
1407
1408
  // Handle -Xopenmp-target flags
1409
240
  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
240
    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
25
      if (SameTripleAsHost ||
1418
25
          
A->getOption().matches(options::OPT_mcode_object_version_EQ)13
)
1419
12
        DAL->append(A);
1420
13
      else
1421
13
        Modified = true;
1422
25
      continue;
1423
25
    }
1424
1425
215
    unsigned Index;
1426
215
    unsigned Prev;
1427
215
    bool XOpenMPTargetNoTriple =
1428
215
        A->getOption().matches(options::OPT_Xopenmp_target);
1429
1430
215
    if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1431
8
      llvm::Triple TT(getOpenMPTriple(A->getValue(0)));
1432
1433
      // Passing device args: -Xopenmp-target=<triple> -opt=val.
1434
8
      if (TT.getTriple() == getTripleString())
1435
4
        Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1436
4
      else
1437
4
        continue;
1438
207
    } else if (XOpenMPTargetNoTriple) {
1439
      // Passing device args: -Xopenmp-target -opt=val.
1440
0
      Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1441
207
    } else {
1442
207
      DAL->append(A);
1443
207
      continue;
1444
207
    }
1445
1446
    // Parse the argument to -Xopenmp-target.
1447
4
    Prev = Index;
1448
4
    std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1449
4
    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
4
    if (XOpenMPTargetNoTriple && 
XOpenMPTargetArg0
&&
1455
4
        
Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 10
) {
1456
0
      getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1457
0
      continue;
1458
0
    }
1459
4
    XOpenMPTargetArg->setBaseArg(A);
1460
4
    A = XOpenMPTargetArg.release();
1461
4
    AllocatedArgs.push_back(A);
1462
4
    DAL->append(A);
1463
4
    Modified = true;
1464
4
  }
1465
1466
25
  if (Modified)
1467
13
    return DAL;
1468
1469
12
  delete DAL;
1470
12
  return nullptr;
1471
25
}
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
29
    SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1480
29
  const OptTable &Opts = getDriver().getOpts();
1481
29
  unsigned ValuePos = 1;
1482
29
  if (A->getOption().matches(options::OPT_Xarch_device) ||
1483
29
      
A->getOption().matches(options::OPT_Xarch_host)20
)
1484
12
    ValuePos = 0;
1485
1486
29
  unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos));
1487
29
  unsigned Prev = Index;
1488
29
  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
29
  if (!XarchArg || 
Index > Prev + 126
) {
1498
3
    getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1499
3
        << A->getAsString(Args);
1500
3
    return;
1501
26
  } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) {
1502
1
    auto &Diags = getDriver().getDiags();
1503
1
    unsigned DiagID =
1504
1
        Diags.getCustomDiagID(DiagnosticsEngine::Error,
1505
1
                              "invalid Xarch argument: '%0', not all driver "
1506
1
                              "options can be forwared via Xarch argument");
1507
1
    Diags.Report(DiagID) << A->getAsString(Args);
1508
1
    return;
1509
1
  }
1510
25
  XarchArg->setBaseArg(A);
1511
25
  A = XarchArg.release();
1512
25
  if (!AllocatedArgs)
1513
12
    DAL->AddSynthesizedArg(A);
1514
13
  else
1515
13
    AllocatedArgs->push_back(A);
1516
25
}
1517
1518
llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
1519
    const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
1520
    Action::OffloadKind OFK,
1521
51.9k
    SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1522
51.9k
  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1523
51.9k
  bool Modified = false;
1524
1525
51.9k
  bool IsDevice = OFK != Action::OFK_None && 
OFK != Action::OFK_Host786
;
1526
800k
  for (Arg *A : Args) {
1527
800k
    bool NeedTrans = false;
1528
800k
    bool Skip = false;
1529
800k
    if (A->getOption().matches(options::OPT_Xarch_device)) {
1530
18
      NeedTrans = IsDevice;
1531
18
      Skip = !IsDevice;
1532
800k
    } else if (A->getOption().matches(options::OPT_Xarch_host)) {
1533
6
      NeedTrans = !IsDevice;
1534
6
      Skip = IsDevice;
1535
800k
    } else if (A->getOption().matches(options::OPT_Xarch__) && 
IsDevice28
) {
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
1
      if (BoundArch.empty() || A->getValue(0) != BoundArch)
1540
0
        Skip = true;
1541
1
      else
1542
1
        NeedTrans = true;
1543
1
    }
1544
800k
    if (NeedTrans || 
Skip800k
)
1545
25
      Modified = true;
1546
800k
    if (NeedTrans)
1547
13
      TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
1548
800k
    if (!Skip)
1549
800k
      DAL->append(A);
1550
800k
  }
1551
1552
51.9k
  if (Modified)
1553
13
    return DAL;
1554
1555
51.9k
  delete DAL;
1556
51.9k
  return nullptr;
1557
51.9k
}