Coverage Report

Created: 2020-09-22 08:39

/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 "InputInfo.h"
11
#include "ToolChains/Arch/ARM.h"
12
#include "ToolChains/Clang.h"
13
#include "ToolChains/InterfaceStubs.h"
14
#include "ToolChains/Flang.h"
15
#include "clang/Basic/ObjCRuntime.h"
16
#include "clang/Basic/Sanitizers.h"
17
#include "clang/Config/config.h"
18
#include "clang/Driver/Action.h"
19
#include "clang/Driver/Driver.h"
20
#include "clang/Driver/DriverDiagnostic.h"
21
#include "clang/Driver/Job.h"
22
#include "clang/Driver/Options.h"
23
#include "clang/Driver/SanitizerArgs.h"
24
#include "clang/Driver/XRayArgs.h"
25
#include "llvm/ADT/STLExtras.h"
26
#include "llvm/ADT/SmallString.h"
27
#include "llvm/ADT/StringRef.h"
28
#include "llvm/ADT/Triple.h"
29
#include "llvm/ADT/Twine.h"
30
#include "llvm/Config/llvm-config.h"
31
#include "llvm/MC/MCTargetOptions.h"
32
#include "llvm/Option/Arg.h"
33
#include "llvm/Option/ArgList.h"
34
#include "llvm/Option/OptTable.h"
35
#include "llvm/Option/Option.h"
36
#include "llvm/Support/ErrorHandling.h"
37
#include "llvm/Support/FileSystem.h"
38
#include "llvm/Support/Path.h"
39
#include "llvm/Support/TargetParser.h"
40
#include "llvm/Support/TargetRegistry.h"
41
#include "llvm/Support/VersionTuple.h"
42
#include "llvm/Support/VirtualFileSystem.h"
43
#include <cassert>
44
#include <cstddef>
45
#include <cstring>
46
#include <string>
47
48
using namespace clang;
49
using namespace driver;
50
using namespace tools;
51
using namespace llvm;
52
using namespace llvm::opt;
53
54
47.2k
static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
55
47.2k
  return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
56
47.2k
                         options::OPT_fno_rtti, options::OPT_frtti);
57
47.2k
}
58
59
static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
60
                                             const llvm::Triple &Triple,
61
47.2k
                                             const Arg *CachedRTTIArg) {
62
  // Explicit rtti/no-rtti args
63
47.2k
  if (CachedRTTIArg) {
64
20.6k
    if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
65
20.5k
      return ToolChain::RM_Enabled;
66
70
    else
67
70
      return ToolChain::RM_Disabled;
68
26.6k
  }
69
70
  // -frtti is default, except for the PS4 CPU.
71
26.6k
  return (Triple.isPS4CPU()) ? 
ToolChain::RM_Disabled130
:
ToolChain::RM_Enabled26.4k
;
72
26.6k
}
73
74
ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
75
                     const ArgList &Args)
76
    : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
77
47.2k
      CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
78
47.2k
  if (D.CCCIsCXX()) {
79
6.40k
    if (auto CXXStdlibPath = getCXXStdlibPath())
80
7
      getFilePaths().push_back(*CXXStdlibPath);
81
6.40k
  }
82
83
47.2k
  if (auto RuntimePath = getRuntimePath())
84
33
    getLibraryPaths().push_back(*RuntimePath);
85
86
47.2k
  std::string CandidateLibPath = getArchSpecificLibPath();
87
47.2k
  if (getVFS().exists(CandidateLibPath))
88
28
    getFilePaths().push_back(CandidateLibPath);
89
47.2k
}
90
91
87
void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
92
87
  Triple.setEnvironment(Env);
93
87
  if (EffectiveTriple != llvm::Triple())
94
0
    EffectiveTriple.setEnvironment(Env);
95
87
}
96
97
47.2k
ToolChain::~ToolChain() = default;
98
99
193k
llvm::vfs::FileSystem &ToolChain::getVFS() const {
100
193k
  return getDriver().getVFS();
101
193k
}
102
103
207k
bool ToolChain::useIntegratedAs() const {
104
207k
  return Args.hasFlag(options::OPT_fintegrated_as,
105
207k
                      options::OPT_fno_integrated_as,
106
207k
                      IsIntegratedAssemblerDefault());
107
207k
}
108
109
9.62k
bool ToolChain::useRelaxRelocations() const {
110
9.62k
  return ENABLE_X86_RELAX_RELOCATIONS;
111
9.62k
}
112
113
7.59k
bool ToolChain::isNoExecStackDefault() const {
114
7.59k
    return false;
115
7.59k
}
116
117
72.7k
const SanitizerArgs& ToolChain::getSanitizerArgs() const {
118
72.7k
  if (!SanitizerArguments.get())
119
45.3k
    SanitizerArguments.reset(new SanitizerArgs(*this, Args));
120
72.7k
  return *SanitizerArguments.get();
121
72.7k
}
122
123
48.1k
const XRayArgs& ToolChain::getXRayArgs() const {
124
48.1k
  if (!XRayArguments.get())
125
45.2k
    XRayArguments.reset(new XRayArgs(*this, Args));
126
48.1k
  return *XRayArguments.get();
127
48.1k
}
128
129
namespace {
130
131
struct DriverSuffix {
132
  const char *Suffix;
133
  const char *ModeFlag;
134
};
135
136
} // namespace
137
138
126k
static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
139
  // A list of known driver suffixes. Suffixes are compared against the
140
  // program name in order. If there is a match, the frontend type is updated as
141
  // necessary by applying the ModeFlag.
142
126k
  static const DriverSuffix DriverSuffixes[] = {
143
126k
      {"clang", nullptr},
144
126k
      {"clang++", "--driver-mode=g++"},
145
126k
      {"clang-c++", "--driver-mode=g++"},
146
126k
      {"clang-cc", nullptr},
147
126k
      {"clang-cpp", "--driver-mode=cpp"},
148
126k
      {"clang-g++", "--driver-mode=g++"},
149
126k
      {"clang-gcc", nullptr},
150
126k
      {"clang-cl", "--driver-mode=cl"},
151
126k
      {"cc", nullptr},
152
126k
      {"cpp", "--driver-mode=cpp"},
153
126k
      {"cl", "--driver-mode=cl"},
154
126k
      {"++", "--driver-mode=g++"},
155
126k
      {"flang", "--driver-mode=flang"},
156
126k
  };
157
158
791k
  for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); 
++i665k
) {
159
740k
    StringRef Suffix(DriverSuffixes[i].Suffix);
160
740k
    if (ProgName.endswith(Suffix)) {
161
75.5k
      Pos = ProgName.size() - Suffix.size();
162
75.5k
      return &DriverSuffixes[i];
163
75.5k
    }
164
740k
  }
165
51.1k
  return nullptr;
166
126k
}
167
168
/// Normalize the program name from argv[0] by stripping the file extension if
169
/// present and lower-casing the string on Windows.
170
77.7k
static std::string normalizeProgramName(llvm::StringRef Argv0) {
171
77.7k
  std::string ProgName = std::string(llvm::sys::path::stem(Argv0));
172
#ifdef _WIN32
173
  // Transform to lowercase for case insensitive file systems.
174
  std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
175
#endif
176
77.7k
  return ProgName;
177
77.7k
}
178
179
77.7k
static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
180
  // Try to infer frontend type and default target from the program name by
181
  // comparing it against DriverSuffixes in order.
182
183
  // If there is a match, the function tries to identify a target as prefix.
184
  // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
185
  // prefix "x86_64-linux". If such a target prefix is found, it may be
186
  // added via -target as implicit first argument.
187
77.7k
  const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
188
189
77.7k
  if (!DS) {
190
    // Try again after stripping any trailing version number:
191
    // clang++3.5 -> clang++
192
24.4k
    ProgName = ProgName.rtrim("0123456789.");
193
24.4k
    DS = FindDriverSuffix(ProgName, Pos);
194
24.4k
  }
195
196
77.7k
  if (!DS) {
197
    // Try again after stripping trailing -component.
198
    // clang++-tot -> clang++
199
24.4k
    ProgName = ProgName.slice(0, ProgName.rfind('-'));
200
24.4k
    DS = FindDriverSuffix(ProgName, Pos);
201
24.4k
  }
202
77.7k
  return DS;
203
77.7k
}
204
205
ParsedClangName
206
77.7k
ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
207
77.7k
  std::string ProgName = normalizeProgramName(PN);
208
77.7k
  size_t SuffixPos;
209
77.7k
  const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
210
77.7k
  if (!DS)
211
2.19k
    return {};
212
75.5k
  size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
213
214
75.5k
  size_t LastComponent = ProgName.rfind('-', SuffixPos);
215
75.5k
  if (LastComponent == std::string::npos)
216
75.5k
    return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
217
33
  std::string ModeSuffix = ProgName.substr(LastComponent + 1,
218
33
                                           SuffixEnd - LastComponent - 1);
219
220
  // Infer target from the prefix.
221
33
  StringRef Prefix(ProgName);
222
33
  Prefix = Prefix.slice(0, LastComponent);
223
33
  std::string IgnoredError;
224
33
  bool IsRegistered =
225
33
      llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError);
226
33
  return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
227
33
                         IsRegistered};
228
33
}
229
230
23.9k
StringRef ToolChain::getDefaultUniversalArchName() const {
231
  // In universal driver terms, the arch name accepted by -arch isn't exactly
232
  // the same as the ones that appear in the triple. Roughly speaking, this is
233
  // an inverse of the darwin::getArchTypeForDarwinArchName() function.
234
23.9k
  switch (Triple.getArch()) {
235
76
  case llvm::Triple::aarch64:
236
76
    return "arm64";
237
3
  case llvm::Triple::aarch64_32:
238
3
    return "arm64_32";
239
0
  case llvm::Triple::ppc:
240
0
    return "ppc";
241
0
  case llvm::Triple::ppc64:
242
0
    return "ppc64";
243
0
  case llvm::Triple::ppc64le:
244
0
    return "ppc64le";
245
23.8k
  default:
246
23.8k
    return Triple.getArchName();
247
23.9k
  }
248
23.9k
}
249
250
438
std::string ToolChain::getInputFilename(const InputInfo &Input) const {
251
438
  return Input.getFilename();
252
438
}
253
254
806
bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
255
806
  return false;
256
806
}
257
258
43.0k
Tool *ToolChain::getClang() const {
259
43.0k
  if (!Clang)
260
42.4k
    Clang.reset(new tools::Clang(*this));
261
43.0k
  return Clang.get();
262
43.0k
}
263
264
17
Tool *ToolChain::getFlang() const {
265
17
  if (!Flang)
266
16
    Flang.reset(new tools::Flang(*this));
267
17
  return Flang.get();
268
17
}
269
270
0
Tool *ToolChain::buildAssembler() const {
271
0
  return new tools::ClangAs(*this);
272
0
}
273
274
0
Tool *ToolChain::buildLinker() const {
275
0
  llvm_unreachable("Linking is not supported by this toolchain");
276
0
}
277
278
0
Tool *ToolChain::buildStaticLibTool() const {
279
0
  llvm_unreachable("Creating static lib is not supported by this toolchain");
280
0
}
281
282
792
Tool *ToolChain::getAssemble() const {
283
792
  if (!Assemble)
284
768
    Assemble.reset(buildAssembler());
285
792
  return Assemble.get();
286
792
}
287
288
350
Tool *ToolChain::getClangAs() const {
289
350
  if (!Assemble)
290
334
    Assemble.reset(new tools::ClangAs(*this));
291
350
  return Assemble.get();
292
350
}
293
294
6.97k
Tool *ToolChain::getLink() const {
295
6.97k
  if (!Link)
296
6.84k
    Link.reset(buildLinker());
297
6.97k
  return Link.get();
298
6.97k
}
299
300
7
Tool *ToolChain::getStaticLibTool() const {
301
7
  if (!StaticLibTool)
302
7
    StaticLibTool.reset(buildStaticLibTool());
303
7
  return StaticLibTool.get();
304
7
}
305
306
21
Tool *ToolChain::getIfsMerge() const {
307
21
  if (!IfsMerge)
308
21
    IfsMerge.reset(new tools::ifstool::Merger(*this));
309
21
  return IfsMerge.get();
310
21
}
311
312
57
Tool *ToolChain::getOffloadBundler() const {
313
57
  if (!OffloadBundler)
314
41
    OffloadBundler.reset(new tools::OffloadBundler(*this));
315
57
  return OffloadBundler.get();
316
57
}
317
318
65
Tool *ToolChain::getOffloadWrapper() const {
319
65
  if (!OffloadWrapper)
320
65
    OffloadWrapper.reset(new tools::OffloadWrapper(*this));
321
65
  return OffloadWrapper.get();
322
65
}
323
324
7.96k
Tool *ToolChain::getTool(Action::ActionClass AC) const {
325
7.96k
  switch (AC) {
326
792
  case Action::AssembleJobClass:
327
792
    return getAssemble();
328
329
21
  case Action::IfsMergeJobClass:
330
21
    return getIfsMerge();
331
332
6.97k
  case Action::LinkJobClass:
333
6.97k
    return getLink();
334
335
7
  case Action::StaticLibJobClass:
336
7
    return getStaticLibTool();
337
338
0
  case Action::InputClass:
339
0
  case Action::BindArchClass:
340
0
  case Action::OffloadClass:
341
0
  case Action::LipoJobClass:
342
0
  case Action::DsymutilJobClass:
343
0
  case Action::VerifyDebugInfoJobClass:
344
0
    llvm_unreachable("Invalid tool kind.");
345
346
45
  case Action::CompileJobClass:
347
45
  case Action::PrecompileJobClass:
348
45
  case Action::HeaderModulePrecompileJobClass:
349
45
  case Action::PreprocessJobClass:
350
45
  case Action::AnalyzeJobClass:
351
45
  case Action::MigrateJobClass:
352
45
  case Action::VerifyPCHJobClass:
353
45
  case Action::BackendJobClass:
354
45
    return getClang();
355
356
57
  case Action::OffloadBundlingJobClass:
357
57
  case Action::OffloadUnbundlingJobClass:
358
57
    return getOffloadBundler();
359
360
65
  case Action::OffloadWrapperJobClass:
361
65
    return getOffloadWrapper();
362
0
  }
363
364
0
  llvm_unreachable("Invalid tool kind.");
365
0
}
366
367
static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
368
1.15k
                                             const ArgList &Args) {
369
1.15k
  const llvm::Triple &Triple = TC.getTriple();
370
1.15k
  bool IsWindows = Triple.isOSWindows();
371
372
1.15k
  if (TC.getArch() == llvm::Triple::arm || 
TC.getArch() == llvm::Triple::armeb1.08k
)
373
67
    return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && 
!IsWindows24
)
374
12
               ? "armhf"
375
55
               : "arm";
376
377
  // For historic reasons, Android library is using i686 instead of i386.
378
1.08k
  if (TC.getArch() == llvm::Triple::x86 && 
Triple.isAndroid()111
)
379
1
    return "i686";
380
381
1.08k
  return llvm::Triple::getArchTypeName(TC.getArch());
382
1.08k
}
383
384
57.1k
StringRef ToolChain::getOSLibName() const {
385
57.1k
  switch (Triple.getOS()) {
386
556
  case llvm::Triple::FreeBSD:
387
556
    return "freebsd";
388
997
  case llvm::Triple::NetBSD:
389
997
    return "netbsd";
390
207
  case llvm::Triple::OpenBSD:
391
207
    return "openbsd";
392
191
  case llvm::Triple::Solaris:
393
191
    return "sunos";
394
55.1k
  default:
395
55.1k
    return getOS();
396
57.1k
  }
397
57.1k
}
398
399
10.9k
std::string ToolChain::getCompilerRTPath() const {
400
10.9k
  SmallString<128> Path(getDriver().ResourceDir);
401
10.9k
  if (Triple.isOSUnknown()) {
402
1.02k
    llvm::sys::path::append(Path, "lib");
403
9.90k
  } else {
404
9.90k
    llvm::sys::path::append(Path, "lib", getOSLibName());
405
9.90k
  }
406
10.9k
  return std::string(Path.str());
407
10.9k
}
408
409
std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
410
                                             StringRef Component, FileType Type,
411
2.33k
                                             bool AddArch) const {
412
2.33k
  const llvm::Triple &TT = getTriple();
413
2.33k
  bool IsITANMSVCWindows =
414
2.33k
      TT.isWindowsMSVCEnvironment() || 
TT.isWindowsItaniumEnvironment()2.18k
;
415
416
2.33k
  const char *Prefix =
417
2.33k
      IsITANMSVCWindows || 
Type == ToolChain::FT_Object2.15k
?
""585
:
"lib"1.74k
;
418
2.33k
  const char *Suffix;
419
2.33k
  switch (Type) {
420
412
  case ToolChain::FT_Object:
421
412
    Suffix = IsITANMSVCWindows ? 
".obj"0
: ".o";
422
412
    break;
423
1.84k
  case ToolChain::FT_Static:
424
1.66k
    Suffix = IsITANMSVCWindows ? 
".lib"173
: ".a";
425
1.84k
    break;
426
78
  case ToolChain::FT_Shared:
427
78
    Suffix = Triple.isOSWindows()
428
4
                 ? (Triple.isWindowsGNUEnvironment() ? ".dll.a" : 
".lib"0
)
429
74
                 : ".so";
430
78
    break;
431
2.33k
  }
432
433
2.33k
  std::string ArchAndEnv;
434
2.33k
  if (AddArch) {
435
1.15k
    StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
436
1.12k
    const char *Env = TT.isAndroid() ? 
"-android"29
: "";
437
1.15k
    ArchAndEnv = ("-" + Arch + Env).str();
438
1.15k
  }
439
2.33k
  return (Prefix + Twine("clang_rt.") + Component + ArchAndEnv + Suffix).str();
440
2.33k
}
441
442
std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
443
1.18k
                                     FileType Type) const {
444
  // Check for runtime files in the new layout without the architecture first.
445
1.18k
  std::string CRTBasename =
446
1.18k
      getCompilerRTBasename(Args, Component, Type, /*AddArch=*/false);
447
56
  for (const auto &LibPath : getLibraryPaths()) {
448
56
    SmallString<128> P(LibPath);
449
56
    llvm::sys::path::append(P, CRTBasename);
450
56
    if (getVFS().exists(P))
451
52
      return std::string(P.str());
452
56
  }
453
454
  // Fall back to the old expected compiler-rt name if the new one does not
455
  // exist.
456
1.12k
  CRTBasename = getCompilerRTBasename(Args, Component, Type, /*AddArch=*/true);
457
1.12k
  SmallString<128> Path(getCompilerRTPath());
458
1.12k
  llvm::sys::path::append(Path, CRTBasename);
459
1.12k
  return std::string(Path.str());
460
1.18k
}
461
462
const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
463
                                              StringRef Component,
464
828
                                              FileType Type) const {
465
828
  return Args.MakeArgString(getCompilerRT(Args, Component, Type));
466
828
}
467
468
469
47.2k
Optional<std::string> ToolChain::getRuntimePath() const {
470
47.2k
  SmallString<128> P;
471
472
  // First try the triple passed to driver as --target=<triple>.
473
47.2k
  P.assign(D.ResourceDir);
474
47.2k
  llvm::sys::path::append(P, "lib", D.getTargetTriple());
475
47.2k
  if (getVFS().exists(P))
476
33
    return llvm::Optional<std::string>(std::string(P.str()));
477
478
  // Second try the normalized triple.
479
47.1k
  P.assign(D.ResourceDir);
480
47.1k
  llvm::sys::path::append(P, "lib", Triple.str());
481
47.1k
  if (getVFS().exists(P))
482
0
    return llvm::Optional<std::string>(std::string(P.str()));
483
484
47.1k
  return None;
485
47.1k
}
486
487
6.44k
Optional<std::string> ToolChain::getCXXStdlibPath() const {
488
6.44k
  SmallString<128> P;
489
490
  // First try the triple passed to driver as --target=<triple>.
491
6.44k
  P.assign(D.Dir);
492
6.44k
  llvm::sys::path::append(P, "..", "lib", D.getTargetTriple(), "c++");
493
6.44k
  if (getVFS().exists(P))
494
34
    return llvm::Optional<std::string>(std::string(P.str()));
495
496
  // Second try the normalized triple.
497
6.41k
  P.assign(D.Dir);
498
6.41k
  llvm::sys::path::append(P, "..", "lib", Triple.str(), "c++");
499
6.41k
  if (getVFS().exists(P))
500
0
    return llvm::Optional<std::string>(std::string(P.str()));
501
502
6.41k
  return None;
503
6.41k
}
504
505
47.2k
std::string ToolChain::getArchSpecificLibPath() const {
506
47.2k
  SmallString<128> Path(getDriver().ResourceDir);
507
47.2k
  llvm::sys::path::append(Path, "lib", getOSLibName(),
508
47.2k
                          llvm::Triple::getArchTypeName(getArch()));
509
47.2k
  return std::string(Path.str());
510
47.2k
}
511
512
7.14k
bool ToolChain::needsProfileRT(const ArgList &Args) {
513
7.14k
  if (Args.hasArg(options::OPT_noprofilelib))
514
4
    return false;
515
516
7.14k
  return Args.hasArg(options::OPT_fprofile_generate) ||
517
7.14k
         Args.hasArg(options::OPT_fprofile_generate_EQ) ||
518
7.14k
         Args.hasArg(options::OPT_fcs_profile_generate) ||
519
7.14k
         Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
520
7.14k
         Args.hasArg(options::OPT_fprofile_instr_generate) ||
521
7.09k
         Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
522
7.09k
         Args.hasArg(options::OPT_fcreate_profile) ||
523
7.09k
         Args.hasArg(options::OPT_forder_file_instrumentation);
524
7.14k
}
525
526
47.8k
bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
527
47.8k
  return Args.hasArg(options::OPT_coverage) ||
528
47.8k
         Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
529
47.8k
                      false);
530
47.8k
}
531
532
51.4k
Tool *ToolChain::SelectTool(const JobAction &JA) const {
533
51.4k
  if (D.IsFlangMode() && 
getDriver().ShouldUseFlangCompiler(JA)20
)
return getFlang()17
;
534
51.4k
  if (getDriver().ShouldUseClangCompiler(JA)) 
return getClang()43.0k
;
535
8.41k
  Action::ActionClass AC = JA.getKind();
536
8.41k
  if (AC == Action::AssembleJobClass && 
useIntegratedAs()1.14k
)
537
350
    return getClangAs();
538
8.06k
  return getTool(AC);
539
8.06k
}
540
541
9.37k
std::string ToolChain::GetFilePath(const char *Name) const {
542
9.37k
  return D.GetFilePath(Name, *this);
543
9.37k
}
544
545
8.27k
std::string ToolChain::GetProgramPath(const char *Name) const {
546
8.27k
  return D.GetProgramPath(Name, *this);
547
8.27k
}
548
549
5.91k
std::string ToolChain::GetLinkerPath() const {
550
  // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
551
  // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
552
5.91k
  const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
553
5.65k
  StringRef UseLinker = A ? 
A->getValue()259
: CLANG_DEFAULT_LINKER;
554
555
  // --ld-path= takes precedence over -fuse-ld= and specifies the executable
556
  // name. -B, COMPILER_PATH and PATH and consulted if the value does not
557
  // contain a path component separator.
558
5.91k
  if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
559
11
    std::string Path(A->getValue());
560
11
    if (!Path.empty()) {
561
10
      if (llvm::sys::path::parent_path(Path).empty())
562
5
        Path = GetProgramPath(A->getValue());
563
10
      if (llvm::sys::fs::can_execute(Path))
564
8
        return std::string(Path);
565
3
    }
566
3
    getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
567
3
    return GetProgramPath(getDefaultLinker());
568
3
  }
569
  // If we're passed -fuse-ld= with no argument, or with the argument ld,
570
  // then use whatever the default system linker is.
571
5.90k
  if (UseLinker.empty() || 
UseLinker == "ld"258
) {
572
5.78k
    const char *DefaultLinker = getDefaultLinker();
573
5.78k
    if (llvm::sys::path::is_absolute(DefaultLinker))
574
22
      return std::string(DefaultLinker);
575
5.76k
    else
576
5.76k
      return GetProgramPath(DefaultLinker);
577
120
  }
578
579
  // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
580
  // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
581
  // to a relative path is surprising. This is more complex due to priorities
582
  // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
583
120
  if (UseLinker.find('/') != StringRef::npos)
584
3
    getDriver().Diag(diag::warn_drv_fuse_ld_path);
585
586
120
  if (llvm::sys::path::is_absolute(UseLinker)) {
587
    // If we're passed what looks like an absolute path, don't attempt to
588
    // second-guess that.
589
3
    if (llvm::sys::fs::can_execute(UseLinker))
590
0
      return std::string(UseLinker);
591
117
  } else {
592
117
    llvm::SmallString<8> LinkerName;
593
117
    if (Triple.isOSDarwin())
594
0
      LinkerName.append("ld64.");
595
117
    else
596
117
      LinkerName.append("ld.");
597
117
    LinkerName.append(UseLinker);
598
599
117
    std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
600
117
    if (llvm::sys::fs::can_execute(LinkerPath))
601
48
      return LinkerPath;
602
72
  }
603
604
72
  if (A)
605
72
    getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
606
607
72
  return GetProgramPath(getDefaultLinker());
608
72
}
609
610
4
std::string ToolChain::GetStaticLibToolPath() const {
611
  // TODO: Add support for static lib archiving on Windows
612
4
  return GetProgramPath("llvm-ar");
613
4
}
614
615
41.3k
types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
616
41.3k
  types::ID id = types::lookupTypeForExtension(Ext);
617
618
  // Flang always runs the preprocessor and has no notion of "preprocessed
619
  // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
620
  // them differently.
621
41.3k
  if (D.IsFlangMode() && 
id == types::TY_PP_Fortran18
)
622
10
    id = types::TY_Fortran;
623
624
41.3k
  return id;
625
41.3k
}
626
627
525
bool ToolChain::HasNativeLLVMSupport() const {
628
525
  return false;
629
525
}
630
631
2.37k
bool ToolChain::isCrossCompiling() const {
632
2.37k
  llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
633
2.37k
  switch (HostTriple.getArch()) {
634
  // The A32/T32/T16 instruction sets are not separate architectures in this
635
  // context.
636
0
  case llvm::Triple::arm:
637
0
  case llvm::Triple::armeb:
638
0
  case llvm::Triple::thumb:
639
0
  case llvm::Triple::thumbeb:
640
0
    return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
641
0
           getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
642
2.37k
  default:
643
2.37k
    return HostTriple.getArch() != getArch();
644
2.37k
  }
645
2.37k
}
646
647
24.9k
ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
648
23.4k
  return ObjCRuntime(isNonFragile ? 
ObjCRuntime::GNUstep1.43k
: ObjCRuntime::GCC,
649
24.9k
                     VersionTuple());
650
24.9k
}
651
652
llvm::ExceptionHandling
653
24.4k
ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
654
24.4k
  return llvm::ExceptionHandling::None;
655
24.4k
}
656
657
14
bool ToolChain::isThreadModelSupported(const StringRef Model) const {
658
14
  if (Model == "single") {
659
    // FIXME: 'single' is only supported on ARM and WebAssembly so far.
660
5
    return Triple.getArch() == llvm::Triple::arm ||
661
2
           Triple.getArch() == llvm::Triple::armeb ||
662
2
           Triple.getArch() == llvm::Triple::thumb ||
663
2
           Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
664
9
  } else if (Model == "posix")
665
5
    return true;
666
667
4
  return false;
668
4
}
669
670
std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
671
51.6k
                                         types::ID InputType) const {
672
51.6k
  switch (getTriple().getArch()) {
673
15.3k
  default:
674
15.3k
    return getTripleString();
675
676
32.5k
  case llvm::Triple::x86_64: {
677
32.5k
    llvm::Triple Triple = getTriple();
678
32.5k
    if (!Triple.isOSBinFormatMachO())
679
11.2k
      return getTripleString();
680
681
21.3k
    if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
682
      // x86_64h goes in the triple. Other -march options just use the
683
      // vanilla triple we already have.
684
2
      StringRef MArch = A->getValue();
685
2
      if (MArch == "x86_64h")
686
0
        Triple.setArchName(MArch);
687
2
    }
688
21.3k
    return Triple.getTriple();
689
21.3k
  }
690
1.22k
  case llvm::Triple::aarch64: {
691
1.22k
    llvm::Triple Triple = getTriple();
692
1.22k
    if (!Triple.isOSBinFormatMachO())
693
1.09k
      return getTripleString();
694
695
    // FIXME: older versions of ld64 expect the "arm64" component in the actual
696
    // triple string and query it to determine whether an LTO file can be
697
    // handled. Remove this when we don't care any more.
698
129
    Triple.setArchName("arm64");
699
129
    return Triple.getTriple();
700
129
  }
701
7
  case llvm::Triple::aarch64_32:
702
7
    return getTripleString();
703
2.46k
  case llvm::Triple::arm:
704
2.46k
  case llvm::Triple::armeb:
705
2.46k
  case llvm::Triple::thumb:
706
2.46k
  case llvm::Triple::thumbeb: {
707
    // FIXME: Factor into subclasses.
708
2.46k
    llvm::Triple Triple = getTriple();
709
2.46k
    bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
710
2.31k
                       getTriple().getArch() == llvm::Triple::thumbeb;
711
712
    // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
713
    // '-mbig-endian'/'-EB'.
714
2.46k
    if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
715
231
                                 options::OPT_mbig_endian)) {
716
231
      IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
717
231
    }
718
719
    // Thumb2 is the default for V7 on Darwin.
720
    //
721
    // FIXME: Thumb should just be another -target-feaure, not in the triple.
722
2.46k
    StringRef MCPU, MArch;
723
2.46k
    if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
724
552
      MCPU = A->getValue();
725
2.46k
    if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
726
832
      MArch = A->getValue();
727
2.46k
    std::string CPU =
728
2.46k
        Triple.isOSBinFormatMachO()
729
421
            ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
730
2.04k
            : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
731
2.46k
    StringRef Suffix =
732
2.46k
      tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
733
2.46k
    bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
734
2.46k
    bool ThumbDefault = IsMProfile || 
(2.19k
ARM::parseArchVersion(Suffix) == 72.19k
&&
735
884
                                       getTriple().isOSBinFormatMachO());
736
    // FIXME: this is invalid for WindowsCE
737
2.46k
    if (getTriple().isOSWindows())
738
81
      ThumbDefault = true;
739
2.46k
    std::string ArchName;
740
2.46k
    if (IsBigEndian)
741
284
      ArchName = "armeb";
742
2.18k
    else
743
2.18k
      ArchName = "arm";
744
745
    // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
746
    // M-Class CPUs/architecture variants, which is not supported.
747
2.46k
    bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
748
2.46k
                                          options::OPT_mno_thumb, ThumbDefault);
749
2.46k
    if (IsMProfile && 
ARMModeRequested277
) {
750
6
      if (!MCPU.empty())
751
2
        getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
752
4
       else
753
4
        getDriver().Diag(diag::err_arch_unsupported_isa)
754
4
          << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
755
6
    }
756
757
    // Check to see if an explicit choice to use thumb has been made via
758
    // -mthumb. For assembler files we must check for -mthumb in the options
759
    // passed to the assembler via -Wa or -Xassembler.
760
2.46k
    bool IsThumb = false;
761
2.46k
    if (InputType != types::TY_PP_Asm)
762
2.36k
      IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
763
2.36k
                              ThumbDefault);
764
101
    else {
765
      // Ideally we would check for these flags in
766
      // CollectArgsForIntegratedAssembler but we can't change the ArchName at
767
      // that point. There is no assembler equivalent of -mno-thumb, -marm, or
768
      // -mno-arm.
769
101
      for (const auto *A :
770
14
           Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
771
14
        for (StringRef Value : A->getValues()) {
772
14
          if (Value == "-mthumb")
773
2
            IsThumb = true;
774
14
        }
775
14
      }
776
101
    }
777
    // Assembly files should start in ARM mode, unless arch is M-profile, or
778
    // -mthumb has been passed explicitly to the assembler. Windows is always
779
    // thumb.
780
2.46k
    if (IsThumb || 
IsMProfile1.53k
||
getTriple().isOSWindows()1.51k
) {
781
955
      if (IsBigEndian)
782
100
        ArchName = "thumbeb";
783
855
      else
784
855
        ArchName = "thumb";
785
955
    }
786
2.46k
    Triple.setArchName(ArchName + Suffix.str());
787
788
2.46k
    return Triple.getTriple();
789
2.46k
  }
790
51.6k
  }
791
51.6k
}
792
793
std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
794
29.5k
                                                   types::ID InputType) const {
795
29.5k
  return ComputeLLVMTriple(Args, InputType);
796
29.5k
}
797
798
12
std::string ToolChain::computeSysRoot() const {
799
12
  return D.SysRoot;
800
12
}
801
802
void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
803
11.3k
                                          ArgStringList &CC1Args) const {
804
  // Each toolchain should provide the appropriate include flags.
805
11.3k
}
806
807
void ToolChain::addClangTargetOptions(
808
    const ArgList &DriverArgs, ArgStringList &CC1Args,
809
7.90k
    Action::OffloadKind DeviceOffloadKind) const {}
810
811
24.8k
void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
812
813
void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
814
2.20k
                                 llvm::opt::ArgStringList &CmdArgs) const {
815
2.20k
  if (!needsProfileRT(Args) && 
!needsGCovInstrumentation(Args)2.18k
)
816
2.17k
    return;
817
818
24
  CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
819
24
}
820
821
ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
822
9.92k
    const ArgList &Args) const {
823
9.92k
  const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
824
8.81k
  StringRef LibName = A ? 
A->getValue()1.11k
: CLANG_DEFAULT_RTLIB;
825
826
  // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
827
9.92k
  if (LibName == "compiler-rt")
828
126
    return ToolChain::RLT_CompilerRT;
829
9.79k
  else if (LibName == "libgcc")
830
82
    return ToolChain::RLT_Libgcc;
831
9.71k
  else if (LibName == "platform")
832
896
    return GetDefaultRuntimeLibType();
833
834
8.82k
  if (A)
835
6
    getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
836
837
8.82k
  return GetDefaultRuntimeLibType();
838
8.82k
}
839
840
ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
841
3.01k
    const ArgList &Args) const {
842
3.01k
  const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
843
3.00k
  StringRef LibName = A ? 
A->getValue()15
: CLANG_DEFAULT_UNWINDLIB;
844
845
3.01k
  if (LibName == "none")
846
0
    return ToolChain::UNW_None;
847
3.01k
  else if (LibName == "platform" || LibName == "") {
848
3.00k
    ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
849
3.00k
    if (RtLibType == ToolChain::RLT_CompilerRT)
850
99
      return ToolChain::UNW_None;
851
2.90k
    else if (RtLibType == ToolChain::RLT_Libgcc)
852
2.90k
      return ToolChain::UNW_Libgcc;
853
15
  } else if (LibName == "libunwind") {
854
12
    if (GetRuntimeLibType(Args) == RLT_Libgcc)
855
6
      getDriver().Diag(diag::err_drv_incompatible_unwindlib);
856
12
    return ToolChain::UNW_CompilerRT;
857
3
  } else if (LibName == "libgcc")
858
3
    return ToolChain::UNW_Libgcc;
859
860
0
  if (A)
861
0
    getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
862
0
        << A->getAsString(Args);
863
864
0
  return GetDefaultUnwindLibType();
865
0
}
866
867
67.3k
ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
868
67.3k
  const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
869
37.1k
  StringRef LibName = A ? A->getValue() : 
CLANG_DEFAULT_CXX_STDLIB30.1k
;
870
871
  // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
872
67.3k
  if (LibName == "libc++")
873
36.8k
    return ToolChain::CST_Libcxx;
874
30.5k
  else if (LibName == "libstdc++")
875
240
    return ToolChain::CST_Libstdcxx;
876
30.3k
  else if (LibName == "platform")
877
117
    return GetDefaultCXXStdlibType();
878
879
30.1k
  if (A)
880
0
    getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
881
882
30.1k
  return GetDefaultCXXStdlibType();
883
30.1k
}
884
885
/// Utility function to add a system include directory to CC1 arguments.
886
/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
887
                                            ArgStringList &CC1Args,
888
83.0k
                                            const Twine &Path) {
889
83.0k
  CC1Args.push_back("-internal-isystem");
890
83.0k
  CC1Args.push_back(DriverArgs.MakeArgString(Path));
891
83.0k
}
892
893
/// Utility function to add a system include directory with extern "C"
894
/// semantics to CC1 arguments.
895
///
896
/// Note that this should be used rarely, and only for directories that
897
/// historically and for legacy reasons are treated as having implicit extern
898
/// "C" semantics. These semantics are *ignored* by and large today, but its
899
/// important to preserve the preprocessor changes resulting from the
900
/// classification.
901
/*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
902
                                                   ArgStringList &CC1Args,
903
28.8k
                                                   const Twine &Path) {
904
28.8k
  CC1Args.push_back("-internal-externc-isystem");
905
28.8k
  CC1Args.push_back(DriverArgs.MakeArgString(Path));
906
28.8k
}
907
908
void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
909
                                                ArgStringList &CC1Args,
910
300
                                                const Twine &Path) {
911
300
  if (llvm::sys::fs::exists(Path))
912
296
    addExternCSystemInclude(DriverArgs, CC1Args, Path);
913
300
}
914
915
/// Utility function to add a list of system include directories to CC1.
916
/*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
917
                                             ArgStringList &CC1Args,
918
0
                                             ArrayRef<StringRef> Paths) {
919
0
  for (const auto &Path : Paths) {
920
0
    CC1Args.push_back("-internal-isystem");
921
0
    CC1Args.push_back(DriverArgs.MakeArgString(Path));
922
0
  }
923
0
}
924
925
void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
926
12.6k
                                             ArgStringList &CC1Args) const {
927
  // Header search paths should be handled by each of the subclasses.
928
  // Historically, they have not been, and instead have been handled inside of
929
  // the CC1-layer frontend. As the logic is hoisted out, this generic function
930
  // will slowly stop being called.
931
  //
932
  // While it is being called, replicate a bit of a hack to propagate the
933
  // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
934
  // header search paths with it. Once all systems are overriding this
935
  // function, the CC1 flag and this line can be removed.
936
12.6k
  DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
937
12.6k
}
938
939
void ToolChain::AddClangCXXStdlibIsystemArgs(
940
    const llvm::opt::ArgList &DriverArgs,
941
8
    llvm::opt::ArgStringList &CC1Args) const {
942
8
  DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
943
8
  if (!DriverArgs.hasArg(options::OPT_nostdincxx))
944
6
    for (const auto &P :
945
6
         DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
946
10
      addSystemInclude(DriverArgs, CC1Args, P);
947
8
}
948
949
3.90k
bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
950
3.90k
  return getDriver().CCCIsCXX() &&
951
2.82k
         !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
952
2.82k
                      options::OPT_nostdlibxx);
953
3.90k
}
954
955
void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
956
69
                                    ArgStringList &CmdArgs) const {
957
69
  assert(!Args.hasArg(options::OPT_nostdlibxx) &&
958
69
         "should not have called this");
959
69
  CXXStdlibType Type = GetCXXStdlibType(Args);
960
961
69
  switch (Type) {
962
28
  case ToolChain::CST_Libcxx:
963
28
    CmdArgs.push_back("-lc++");
964
28
    break;
965
966
41
  case ToolChain::CST_Libstdcxx:
967
41
    CmdArgs.push_back("-lstdc++");
968
41
    break;
969
69
  }
970
69
}
971
972
void ToolChain::AddFilePathLibArgs(const ArgList &Args,
973
2.01k
                                   ArgStringList &CmdArgs) const {
974
2.01k
  for (const auto &LibPath : getFilePaths())
975
5.35k
    if(LibPath.length() > 0)
976
5.29k
      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
977
2.01k
}
978
979
void ToolChain::AddCCKextLibArgs(const ArgList &Args,
980
0
                                 ArgStringList &CmdArgs) const {
981
0
  CmdArgs.push_back("-lcc_kext");
982
0
}
983
984
bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args,
985
6.44k
                                           std::string &Path) const {
986
  // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
987
  // (to keep the linker options consistent with gcc and clang itself).
988
6.44k
  if (!isOptimizationLevelFast(Args)) {
989
    // Check if -ffast-math or -funsafe-math.
990
6.42k
    Arg *A =
991
6.42k
      Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
992
6.42k
                      options::OPT_funsafe_math_optimizations,
993
6.42k
                      options::OPT_fno_unsafe_math_optimizations);
994
995
6.42k
    if (!A || 
A->getOption().getID() == options::OPT_fno_fast_math20
||
996
13
        A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
997
6.40k
      return false;
998
39
  }
999
  // If crtfastmath.o exists add it to the arguments.
1000
39
  Path = GetFilePath("crtfastmath.o");
1001
39
  return (Path != "crtfastmath.o"); // Not found.
1002
39
}
1003
1004
bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args,
1005
1.53k
                                              ArgStringList &CmdArgs) const {
1006
1.53k
  std::string Path;
1007
1.53k
  if (isFastMathRuntimeAvailable(Args, Path)) {
1008
9
    CmdArgs.push_back(Args.MakeArgString(Path));
1009
9
    return true;
1010
9
  }
1011
1012
1.52k
  return false;
1013
1.52k
}
1014
1015
45.3k
SanitizerMask ToolChain::getSupportedSanitizers() const {
1016
  // Return sanitizers which don't require runtime support and are not
1017
  // platform dependent.
1018
1019
45.3k
  SanitizerMask Res =
1020
45.3k
      (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
1021
45.3k
       ~SanitizerKind::Function) |
1022
45.3k
      (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1023
45.3k
      SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
1024
45.3k
      SanitizerKind::UnsignedIntegerOverflow |
1025
45.3k
      SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
1026
45.3k
      SanitizerKind::Nullability | SanitizerKind::LocalBounds;
1027
45.3k
  if (getTriple().getArch() == llvm::Triple::x86 ||
1028
35.5k
      getTriple().getArch() == llvm::Triple::x86_64 ||
1029
4.99k
      getTriple().getArch() == llvm::Triple::arm || 
getTriple().isWasm()3.44k
||
1030
3.36k
      getTriple().isAArch64())
1031
43.1k
    Res |= SanitizerKind::CFIICall;
1032
45.3k
  if (getTriple().getArch() == llvm::Triple::x86_64 ||
1033
14.7k
      getTriple().isAArch64() || 
getTriple().isRISCV()13.6k
)
1034
32.0k
    Res |= SanitizerKind::ShadowCallStack;
1035
45.3k
  if (getTriple().isAArch64())
1036
1.15k
    Res |= SanitizerKind::MemTag;
1037
45.3k
  return Res;
1038
45.3k
}
1039
1040
void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1041
4
                                   ArgStringList &CC1Args) const {}
1042
1043
void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1044
1
                                  ArgStringList &CC1Args) const {}
1045
1046
void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
1047
0
                                    ArgStringList &CC1Args) const {}
1048
1049
38
static VersionTuple separateMSVCFullVersion(unsigned Version) {
1050
38
  if (Version < 100)
1051
2
    return VersionTuple(Version);
1052
1053
36
  if (Version < 10000)
1054
34
    return VersionTuple(Version / 100, Version % 100);
1055
1056
2
  unsigned Build = 0, Factor = 1;
1057
12
  for (; Version > 10000; 
Version = Version / 10, Factor = Factor * 1010
)
1058
10
    Build = Build + (Version % 10) * Factor;
1059
2
  return VersionTuple(Version / 100, Version % 100, Build);
1060
2
}
1061
1062
VersionTuple
1063
ToolChain::computeMSVCVersion(const Driver *D,
1064
51.0k
                              const llvm::opt::ArgList &Args) const {
1065
51.0k
  const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1066
51.0k
  const Arg *MSCompatibilityVersion =
1067
51.0k
      Args.getLastArg(options::OPT_fms_compatibility_version);
1068
1069
51.0k
  if (MSCVersion && 
MSCompatibilityVersion40
) {
1070
2
    if (D)
1071
1
      D->Diag(diag::err_drv_argument_not_allowed_with)
1072
1
          << MSCVersion->getAsString(Args)
1073
1
          << MSCompatibilityVersion->getAsString(Args);
1074
2
    return VersionTuple();
1075
2
  }
1076
1077
51.0k
  if (MSCompatibilityVersion) {
1078
22
    VersionTuple MSVT;
1079
22
    if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
1080
0
      if (D)
1081
0
        D->Diag(diag::err_drv_invalid_value)
1082
0
            << MSCompatibilityVersion->getAsString(Args)
1083
0
            << MSCompatibilityVersion->getValue();
1084
22
    } else {
1085
22
      return MSVT;
1086
22
    }
1087
50.9k
  }
1088
1089
50.9k
  if (MSCVersion) {
1090
38
    unsigned Version = 0;
1091
38
    if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1092
0
      if (D)
1093
0
        D->Diag(diag::err_drv_invalid_value)
1094
0
            << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1095
38
    } else {
1096
38
      return separateMSVCFullVersion(Version);
1097
38
    }
1098
50.9k
  }
1099
1100
50.9k
  return VersionTuple();
1101
50.9k
}
1102
1103
llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
1104
    const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1105
85
    SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
1106
85
  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1107
85
  const OptTable &Opts = getDriver().getOpts();
1108
85
  bool Modified = false;
1109
1110
  // Handle -Xopenmp-target flags
1111
745
  for (auto *A : Args) {
1112
    // Exclude flags which may only apply to the host toolchain.
1113
    // Do not exclude flags when the host triple (AuxTriple)
1114
    // matches the current toolchain triple. If it is not present
1115
    // at all, target and host share a toolchain.
1116
745
    if (A->getOption().matches(options::OPT_m_Group)) {
1117
4
      if (SameTripleAsHost)
1118
1
        DAL->append(A);
1119
3
      else
1120
3
        Modified = true;
1121
4
      continue;
1122
4
    }
1123
1124
741
    unsigned Index;
1125
741
    unsigned Prev;
1126
741
    bool XOpenMPTargetNoTriple =
1127
741
        A->getOption().matches(options::OPT_Xopenmp_target);
1128
1129
741
    if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1130
      // Passing device args: -Xopenmp-target=<triple> -opt=val.
1131
3
      if (A->getValue(0) == getTripleString())
1132
2
        Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1133
1
      else
1134
1
        continue;
1135
738
    } else if (XOpenMPTargetNoTriple) {
1136
      // Passing device args: -Xopenmp-target -opt=val.
1137
44
      Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1138
694
    } else {
1139
694
      DAL->append(A);
1140
694
      continue;
1141
694
    }
1142
1143
    // Parse the argument to -Xopenmp-target.
1144
46
    Prev = Index;
1145
46
    std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1146
46
    if (!XOpenMPTargetArg || 
Index > Prev + 145
) {
1147
1
      getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
1148
1
          << A->getAsString(Args);
1149
1
      continue;
1150
1
    }
1151
45
    if (XOpenMPTargetNoTriple && 
XOpenMPTargetArg43
&&
1152
43
        Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
1153
2
      getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1154
2
      continue;
1155
2
    }
1156
43
    XOpenMPTargetArg->setBaseArg(A);
1157
43
    A = XOpenMPTargetArg.release();
1158
43
    AllocatedArgs.push_back(A);
1159
43
    DAL->append(A);
1160
43
    Modified = true;
1161
43
  }
1162
1163
85
  if (Modified)
1164
45
    return DAL;
1165
1166
40
  delete DAL;
1167
40
  return nullptr;
1168
40
}
1169
1170
// TODO: Currently argument values separated by space e.g.
1171
// -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
1172
// fixed.
1173
void ToolChain::TranslateXarchArgs(
1174
    const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
1175
    llvm::opt::DerivedArgList *DAL,
1176
19
    SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1177
19
  const OptTable &Opts = getDriver().getOpts();
1178
19
  unsigned ValuePos = 1;
1179
19
  if (A->getOption().matches(options::OPT_Xarch_device) ||
1180
13
      A->getOption().matches(options::OPT_Xarch_host))
1181
9
    ValuePos = 0;
1182
1183
19
  unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos));
1184
19
  unsigned Prev = Index;
1185
19
  std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(Args, Index));
1186
1187
  // If the argument parsing failed or more than one argument was
1188
  // consumed, the -Xarch_ argument's parameter tried to consume
1189
  // extra arguments. Emit an error and ignore.
1190
  //
1191
  // We also want to disallow any options which would alter the
1192
  // driver behavior; that isn't going to work in our model. We
1193
  // use isDriverOption() as an approximation, although things
1194
  // like -O4 are going to slip through.
1195
19
  if (!XarchArg || 
Index > Prev + 117
) {
1196
2
    getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1197
2
        << A->getAsString(Args);
1198
2
    return;
1199
17
  } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
1200
1
    getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
1201
1
        << A->getAsString(Args);
1202
1
    return;
1203
1
  }
1204
16
  XarchArg->setBaseArg(A);
1205
16
  A = XarchArg.release();
1206
16
  if (!AllocatedArgs)
1207
6
    DAL->AddSynthesizedArg(A);
1208
10
  else
1209
10
    AllocatedArgs->push_back(A);
1210
16
}
1211
1212
llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
1213
    const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
1214
    Action::OffloadKind OFK,
1215
46.4k
    SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1216
46.4k
  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1217
46.4k
  bool Modified = false;
1218
1219
46.4k
  bool IsGPU = OFK == Action::OFK_Cuda || 
OFK == Action::OFK_HIP46.0k
;
1220
779k
  for (Arg *A : Args) {
1221
779k
    bool NeedTrans = false;
1222
779k
    bool Skip = false;
1223
779k
    if (A->getOption().matches(options::OPT_Xarch_device)) {
1224
12
      NeedTrans = IsGPU;
1225
12
      Skip = !IsGPU;
1226
779k
    } else if (A->getOption().matches(options::OPT_Xarch_host)) {
1227
6
      NeedTrans = !IsGPU;
1228
6
      Skip = IsGPU;
1229
779k
    } else if (A->getOption().matches(options::OPT_Xarch__) && 
IsGPU15
) {
1230
      // Do not translate -Xarch_ options for non CUDA/HIP toolchain since
1231
      // they may need special translation.
1232
      // Skip this argument unless the architecture matches BoundArch
1233
1
      if (BoundArch.empty() || A->getValue(0) != BoundArch)
1234
0
        Skip = true;
1235
1
      else
1236
1
        NeedTrans = true;
1237
1
    }
1238
779k
    if (NeedTrans || 
Skip779k
)
1239
19
      Modified = true;
1240
779k
    if (NeedTrans)
1241
10
      TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
1242
779k
    if (!Skip)
1243
779k
      DAL->append(A);
1244
779k
  }
1245
1246
46.4k
  if (Modified)
1247
13
    return DAL;
1248
1249
46.4k
  delete DAL;
1250
46.4k
  return nullptr;
1251
46.4k
}