Coverage Report

Created: 2021-01-16 07:00

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Driver/ToolChains/Gnu.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- Gnu.cpp - Gnu Tool and ToolChain Implementations -------*- C++ -*-===//
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 "Gnu.h"
10
#include "Arch/ARM.h"
11
#include "Arch/Mips.h"
12
#include "Arch/PPC.h"
13
#include "Arch/RISCV.h"
14
#include "Arch/Sparc.h"
15
#include "Arch/SystemZ.h"
16
#include "CommonArgs.h"
17
#include "Linux.h"
18
#include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
19
#include "clang/Driver/Compilation.h"
20
#include "clang/Driver/Driver.h"
21
#include "clang/Driver/DriverDiagnostic.h"
22
#include "clang/Driver/Options.h"
23
#include "clang/Driver/Tool.h"
24
#include "clang/Driver/ToolChain.h"
25
#include "llvm/Option/ArgList.h"
26
#include "llvm/Support/CodeGen.h"
27
#include "llvm/Support/Path.h"
28
#include "llvm/Support/TargetParser.h"
29
#include "llvm/Support/VirtualFileSystem.h"
30
#include <system_error>
31
32
using namespace clang::driver;
33
using namespace clang::driver::toolchains;
34
using namespace clang;
35
using namespace llvm::opt;
36
37
using tools::addMultilibFlag;
38
using tools::addPathIfExists;
39
40
1.67k
static bool forwardToGCC(const Option &O) {
41
  // LinkerInput options have been forwarded. Don't duplicate.
42
1.67k
  if (O.hasFlag(options::LinkerInput))
43
2
    return false;
44
1.67k
  return O.matches(options::OPT_Link_Group) || 
O.hasFlag(options::LinkOption)1.66k
;
45
1.67k
}
46
47
// Switch CPU names not recognized by GNU assembler to a close CPU that it does
48
// recognize, instead of a lower march from being picked in the absence of a cpu
49
// flag.
50
static void normalizeCPUNamesForAssembler(const ArgList &Args,
51
44
                                          ArgStringList &CmdArgs) {
52
44
  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
53
27
    StringRef CPUArg(A->getValue());
54
27
    if (CPUArg.equals_lower("krait"))
55
1
      CmdArgs.push_back("-mcpu=cortex-a15");
56
26
    else if(CPUArg.equals_lower("kryo"))
57
2
      CmdArgs.push_back("-mcpu=cortex-a57");
58
24
    else
59
24
      Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
60
27
  }
61
44
}
62
63
void tools::gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
64
                                      const InputInfo &Output,
65
                                      const InputInfoList &Inputs,
66
                                      const ArgList &Args,
67
287
                                      const char *LinkingOutput) const {
68
287
  const Driver &D = getToolChain().getDriver();
69
287
  ArgStringList CmdArgs;
70
71
1.67k
  for (const auto &A : Args) {
72
1.67k
    if (forwardToGCC(A->getOption())) {
73
      // It is unfortunate that we have to claim here, as this means
74
      // we will basically never report anything interesting for
75
      // platforms using a generic gcc, even if we are just using gcc
76
      // to get to the assembler.
77
11
      A->claim();
78
79
11
      A->render(Args, CmdArgs);
80
11
    }
81
1.67k
  }
82
83
287
  RenderExtraToolArgs(JA, CmdArgs);
84
85
  // If using a driver driver, force the arch.
86
287
  if (getToolChain().getTriple().isOSDarwin()) {
87
0
    CmdArgs.push_back("-arch");
88
0
    CmdArgs.push_back(
89
0
        Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
90
0
  }
91
92
  // Try to force gcc to match the tool chain we want, if we recognize
93
  // the arch.
94
  //
95
  // FIXME: The triple class should directly provide the information we want
96
  // here.
97
287
  switch (getToolChain().getArch()) {
98
265
  default:
99
265
    break;
100
5
  case llvm::Triple::x86:
101
6
  case llvm::Triple::ppc:
102
6
  case llvm::Triple::ppcle:
103
6
    CmdArgs.push_back("-m32");
104
6
    break;
105
15
  case llvm::Triple::x86_64:
106
15
  case llvm::Triple::ppc64:
107
15
  case llvm::Triple::ppc64le:
108
15
    CmdArgs.push_back("-m64");
109
15
    break;
110
1
  case llvm::Triple::sparcel:
111
1
    CmdArgs.push_back("-EL");
112
1
    break;
113
287
  }
114
115
287
  if (Output.isFilename()) {
116
286
    CmdArgs.push_back("-o");
117
286
    CmdArgs.push_back(Output.getFilename());
118
1
  } else {
119
1
    assert(Output.isNothing() && "Unexpected output");
120
1
    CmdArgs.push_back("-fsyntax-only");
121
1
  }
122
123
287
  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
124
125
  // Only pass -x if gcc will understand it; otherwise hope gcc
126
  // understands the suffix correctly. The main use case this would go
127
  // wrong in is for linker inputs if they happened to have an odd
128
  // suffix; really the only way to get this to happen is a command
129
  // like '-x foobar a.c' which will treat a.c like a linker input.
130
  //
131
  // FIXME: For the linker case specifically, can we safely convert
132
  // inputs into '-Wl,' options?
133
291
  for (const auto &II : Inputs) {
134
    // Don't try to pass LLVM or AST inputs to a generic gcc.
135
291
    if (types::isLLVMIR(II.getType()))
136
0
      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
137
0
          << getToolChain().getTripleString();
138
291
    else if (II.getType() == types::TY_AST)
139
0
      D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
140
291
    else if (II.getType() == types::TY_ModuleFile)
141
0
      D.Diag(diag::err_drv_no_module_support)
142
0
          << getToolChain().getTripleString();
143
144
291
    if (types::canTypeBeUserSpecified(II.getType())) {
145
4
      CmdArgs.push_back("-x");
146
4
      CmdArgs.push_back(types::getTypeName(II.getType()));
147
4
    }
148
149
291
    if (II.isFilename())
150
289
      CmdArgs.push_back(II.getFilename());
151
2
    else {
152
2
      const Arg &A = II.getInputArg();
153
154
      // Reverse translate some rewritten options.
155
2
      if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
156
0
        CmdArgs.push_back("-lstdc++");
157
0
        continue;
158
0
      }
159
160
      // Don't render as input, we need gcc to do the translations.
161
2
      A.render(Args, CmdArgs);
162
2
    }
163
291
  }
164
165
287
  const std::string &customGCCName = D.getCCCGenericGCCName();
166
287
  const char *GCCName;
167
287
  if (!customGCCName.empty())
168
0
    GCCName = customGCCName.c_str();
169
287
  else if (D.CCCIsCXX()) {
170
0
    GCCName = "g++";
171
0
  } else
172
287
    GCCName = "gcc";
173
174
287
  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
175
287
  C.addCommand(std::make_unique<Command>(JA, *this,
176
287
                                         ResponseFileSupport::AtFileCurCP(),
177
287
                                         Exec, CmdArgs, Inputs, Output));
178
287
}
179
180
void tools::gcc::Preprocessor::RenderExtraToolArgs(
181
0
    const JobAction &JA, ArgStringList &CmdArgs) const {
182
0
  CmdArgs.push_back("-E");
183
0
}
184
185
void tools::gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
186
4
                                               ArgStringList &CmdArgs) const {
187
4
  const Driver &D = getToolChain().getDriver();
188
189
4
  switch (JA.getType()) {
190
  // If -flto, etc. are present then make sure not to force assembly output.
191
0
  case types::TY_LLVM_IR:
192
0
  case types::TY_LTO_IR:
193
0
  case types::TY_LLVM_BC:
194
0
  case types::TY_LTO_BC:
195
0
    CmdArgs.push_back("-c");
196
0
    break;
197
  // We assume we've got an "integrated" assembler in that gcc will produce an
198
  // object file itself.
199
2
  case types::TY_Object:
200
2
    CmdArgs.push_back("-c");
201
2
    break;
202
1
  case types::TY_PP_Asm:
203
1
    CmdArgs.push_back("-S");
204
1
    break;
205
1
  case types::TY_Nothing:
206
1
    CmdArgs.push_back("-fsyntax-only");
207
1
    break;
208
0
  default:
209
0
    D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
210
4
  }
211
4
}
212
213
void tools::gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
214
283
                                             ArgStringList &CmdArgs) const {
215
  // The types are (hopefully) good enough.
216
283
}
217
218
// On Arm the endianness of the output file is determined by the target and
219
// can be overridden by the pseudo-target flags '-mlittle-endian'/'-EL' and
220
// '-mbig-endian'/'-EB'. Unlike other targets the flag does not result in a
221
// normalized triple so we must handle the flag here.
222
static bool isArmBigEndian(const llvm::Triple &Triple,
223
515
                           const ArgList &Args) {
224
515
  bool IsBigEndian = false;
225
515
  switch (Triple.getArch()) {
226
28
  case llvm::Triple::armeb:
227
37
  case llvm::Triple::thumbeb:
228
37
    IsBigEndian = true;
229
37
    LLVM_FALLTHROUGH;
230
419
  case llvm::Triple::arm:
231
434
  case llvm::Triple::thumb:
232
434
    if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
233
13
                               options::OPT_mbig_endian))
234
13
      IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
235
434
    break;
236
81
  default:
237
81
    break;
238
515
  }
239
515
  return IsBigEndian;
240
515
}
241
242
1.53k
static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
243
1.53k
  switch (T.getArch()) {
244
261
  case llvm::Triple::x86:
245
261
    if (T.isOSIAMCU())
246
8
      return "elf_iamcu";
247
253
    return "elf_i386";
248
77
  case llvm::Triple::aarch64:
249
77
    return "aarch64linux";
250
4
  case llvm::Triple::aarch64_be:
251
4
    return "aarch64linuxb";
252
181
  case llvm::Triple::arm:
253
186
  case llvm::Triple::thumb:
254
195
  case llvm::Triple::armeb:
255
200
  case llvm::Triple::thumbeb:
256
186
    return isArmBigEndian(T, Args) ? 
"armelfb_linux_eabi"14
: "armelf_linux_eabi";
257
19
  case llvm::Triple::ppc:
258
19
    if (T.isOSLinux())
259
19
      return "elf32ppclinux";
260
0
    return "elf32ppc";
261
3
  case llvm::Triple::ppcle:
262
3
    if (T.isOSLinux())
263
3
      return "elf32lppclinux";
264
0
    return "elf32lppc";
265
53
  case llvm::Triple::ppc64:
266
53
    return "elf64ppc";
267
58
  case llvm::Triple::ppc64le:
268
58
    return "elf64lppc";
269
4
  case llvm::Triple::riscv32:
270
4
    return "elf32lriscv";
271
8
  case llvm::Triple::riscv64:
272
8
    return "elf64lriscv";
273
2
  case llvm::Triple::sparc:
274
3
  case llvm::Triple::sparcel:
275
3
    return "elf32_sparc";
276
2
  case llvm::Triple::sparcv9:
277
2
    return "elf64_sparc";
278
61
  case llvm::Triple::mips:
279
61
    return "elf32btsmip";
280
76
  case llvm::Triple::mipsel:
281
76
    return "elf32ltsmip";
282
48
  case llvm::Triple::mips64:
283
48
    if (tools::mips::hasMipsAbiArg(Args, "n32") ||
284
32
        T.getEnvironment() == llvm::Triple::GNUABIN32)
285
17
      return "elf32btsmipn32";
286
31
    return "elf64btsmip";
287
53
  case llvm::Triple::mips64el:
288
53
    if (tools::mips::hasMipsAbiArg(Args, "n32") ||
289
36
        T.getEnvironment() == llvm::Triple::GNUABIN32)
290
17
      return "elf32ltsmipn32";
291
36
    return "elf64ltsmip";
292
10
  case llvm::Triple::systemz:
293
10
    return "elf64_s390";
294
590
  case llvm::Triple::x86_64:
295
590
    if (T.getEnvironment() == llvm::Triple::GNUX32)
296
8
      return "elf32_x86_64";
297
582
    return "elf_x86_64";
298
0
  case llvm::Triple::ve:
299
0
    return "elf64ve";
300
2
  default:
301
2
    return nullptr;
302
1.53k
  }
303
1.53k
}
304
305
1.53k
static bool getPIE(const ArgList &Args, const ToolChain &TC) {
306
1.53k
  if (Args.hasArg(options::OPT_shared) || 
Args.hasArg(options::OPT_static)1.47k
||
307
1.43k
      Args.hasArg(options::OPT_r) || 
Args.hasArg(options::OPT_static_pie)1.43k
)
308
98
    return false;
309
310
1.43k
  Arg *A = Args.getLastArg(options::OPT_pie, options::OPT_no_pie,
311
1.43k
                           options::OPT_nopie);
312
1.43k
  if (!A)
313
1.37k
    return TC.isPIEDefault();
314
55
  return A->getOption().matches(options::OPT_pie);
315
55
}
316
317
1.53k
static bool getStaticPIE(const ArgList &Args, const ToolChain &TC) {
318
1.53k
  bool HasStaticPIE = Args.hasArg(options::OPT_static_pie);
319
  // -no-pie is an alias for -nopie. So, handling -nopie takes care of
320
  // -no-pie as well.
321
1.53k
  if (HasStaticPIE && 
Args.hasArg(options::OPT_nopie)4
) {
322
1
    const Driver &D = TC.getDriver();
323
1
    const llvm::opt::OptTable &Opts = D.getOpts();
324
1
    const char *StaticPIEName = Opts.getOptionName(options::OPT_static_pie);
325
1
    const char *NoPIEName = Opts.getOptionName(options::OPT_nopie);
326
1
    D.Diag(diag::err_drv_cannot_mix_options) << StaticPIEName << NoPIEName;
327
1
  }
328
1.53k
  return HasStaticPIE;
329
1.53k
}
330
331
1.53k
static bool getStatic(const ArgList &Args) {
332
1.53k
  return Args.hasArg(options::OPT_static) &&
333
32
      !Args.hasArg(options::OPT_static_pie);
334
1.53k
}
335
336
void tools::gnutools::StaticLibTool::ConstructJob(
337
    Compilation &C, const JobAction &JA, const InputInfo &Output,
338
    const InputInfoList &Inputs, const ArgList &Args,
339
4
    const char *LinkingOutput) const {
340
4
  const Driver &D = getToolChain().getDriver();
341
342
  // Silence warning for "clang -g foo.o -o foo"
343
4
  Args.ClaimAllArgs(options::OPT_g_Group);
344
  // and "clang -emit-llvm foo.o -o foo"
345
4
  Args.ClaimAllArgs(options::OPT_emit_llvm);
346
  // and for "clang -w foo.o -o foo". Other warning options are already
347
  // handled somewhere else.
348
4
  Args.ClaimAllArgs(options::OPT_w);
349
  // Silence warnings when linking C code with a C++ '-stdlib' argument.
350
4
  Args.ClaimAllArgs(options::OPT_stdlib_EQ);
351
352
  // ar tool command "llvm-ar <options> <output_file> <input_files>".
353
4
  ArgStringList CmdArgs;
354
  // Create and insert file members with a deterministic index.
355
4
  CmdArgs.push_back("rcsD");
356
4
  CmdArgs.push_back(Output.getFilename());
357
358
14
  for (const auto &II : Inputs) {
359
14
    if (II.isFilename()) {
360
11
       CmdArgs.push_back(II.getFilename());
361
11
    }
362
14
  }
363
364
  // Delete old output archive file if it already exists before generating a new
365
  // archive file.
366
4
  auto OutputFileName = Output.getFilename();
367
4
  if (Output.isFilename() && llvm::sys::fs::exists(OutputFileName)) {
368
0
    if (std::error_code EC = llvm::sys::fs::remove(OutputFileName)) {
369
0
      D.Diag(diag::err_drv_unable_to_remove_file) << EC.message();
370
0
      return;
371
0
    }
372
4
  }
373
374
4
  const char *Exec = Args.MakeArgString(getToolChain().GetStaticLibToolPath());
375
4
  C.addCommand(std::make_unique<Command>(JA, *this,
376
4
                                         ResponseFileSupport::AtFileCurCP(),
377
4
                                         Exec, CmdArgs, Inputs, Output));
378
4
}
379
380
void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
381
                                           const InputInfo &Output,
382
                                           const InputInfoList &Inputs,
383
                                           const ArgList &Args,
384
1.53k
                                           const char *LinkingOutput) const {
385
  // FIXME: The Linker class constructor takes a ToolChain and not a
386
  // Generic_ELF, so the static_cast might return a reference to a invalid
387
  // instance (see PR45061). Ideally, the Linker constructor needs to take a
388
  // Generic_ELF instead.
389
1.53k
  const toolchains::Generic_ELF &ToolChain =
390
1.53k
      static_cast<const toolchains::Generic_ELF &>(getToolChain());
391
1.53k
  const Driver &D = ToolChain.getDriver();
392
393
1.53k
  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
394
395
1.53k
  const llvm::Triple::ArchType Arch = ToolChain.getArch();
396
1.53k
  const bool isAndroid = ToolChain.getTriple().isAndroid();
397
1.53k
  const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
398
1.53k
  const bool IsVE = ToolChain.getTriple().isVE();
399
1.53k
  const bool IsPIE = getPIE(Args, ToolChain);
400
1.53k
  const bool IsStaticPIE = getStaticPIE(Args, ToolChain);
401
1.53k
  const bool IsStatic = getStatic(Args);
402
1.53k
  const bool HasCRTBeginEndFiles =
403
1.53k
      ToolChain.getTriple().hasEnvironment() ||
404
319
      (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
405
406
1.53k
  ArgStringList CmdArgs;
407
408
  // Silence warning for "clang -g foo.o -o foo"
409
1.53k
  Args.ClaimAllArgs(options::OPT_g_Group);
410
  // and "clang -emit-llvm foo.o -o foo"
411
1.53k
  Args.ClaimAllArgs(options::OPT_emit_llvm);
412
  // and for "clang -w foo.o -o foo". Other warning options are already
413
  // handled somewhere else.
414
1.53k
  Args.ClaimAllArgs(options::OPT_w);
415
416
1.53k
  if (!D.SysRoot.empty())
417
318
    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
418
419
1.53k
  if (IsPIE)
420
185
    CmdArgs.push_back("-pie");
421
422
1.53k
  if (IsStaticPIE) {
423
4
    CmdArgs.push_back("-static");
424
4
    CmdArgs.push_back("-pie");
425
4
    CmdArgs.push_back("--no-dynamic-linker");
426
4
    CmdArgs.push_back("-z");
427
4
    CmdArgs.push_back("text");
428
4
  }
429
430
1.53k
  if (ToolChain.isNoExecStackDefault()) {
431
163
    CmdArgs.push_back("-z");
432
163
    CmdArgs.push_back("noexecstack");
433
163
  }
434
435
1.53k
  if (Args.hasArg(options::OPT_rdynamic))
436
5
    CmdArgs.push_back("-export-dynamic");
437
438
1.53k
  if (Args.hasArg(options::OPT_s))
439
0
    CmdArgs.push_back("-s");
440
441
1.53k
  if (Triple.isARM() || 
Triple.isThumb()1.33k
||
Triple.isAArch64()1.33k
) {
442
281
    bool IsBigEndian = isArmBigEndian(Triple, Args);
443
281
    if (IsBigEndian)
444
14
      arm::appendBE8LinkFlag(Args, CmdArgs, Triple);
445
281
    IsBigEndian = IsBigEndian || 
Arch == llvm::Triple::aarch64_be267
;
446
263
    CmdArgs.push_back(IsBigEndian ? 
"-EB"18
: "-EL");
447
281
  }
448
449
  // Most Android ARM64 targets should enable the linker fix for erratum
450
  // 843419. Only non-Cortex-A53 devices are allowed to skip this flag.
451
1.53k
  if (Arch == llvm::Triple::aarch64 && 
isAndroid77
) {
452
42
    std::string CPU = getCPUName(Args, Triple);
453
42
    if (CPU.empty() || CPU == "generic" || 
CPU == "cortex-a53"2
)
454
41
      CmdArgs.push_back("--fix-cortex-a53-843419");
455
42
  }
456
457
  // Android does not allow shared text relocations. Emit a warning if the
458
  // user's code contains any.
459
1.53k
  if (isAndroid)
460
163
      CmdArgs.push_back("--warn-shared-textrel");
461
462
1.53k
  ToolChain.addExtraOpts(CmdArgs);
463
464
1.53k
  CmdArgs.push_back("--eh-frame-hdr");
465
466
1.53k
  if (const char *LDMOption = getLDMOption(ToolChain.getTriple(), Args)) {
467
1.53k
    CmdArgs.push_back("-m");
468
1.53k
    CmdArgs.push_back(LDMOption);
469
2
  } else {
470
2
    D.Diag(diag::err_target_unknown_triple) << Triple.str();
471
2
    return;
472
2
  }
473
474
1.53k
  if (IsStatic) {
475
31
    if (Arch == llvm::Triple::arm || 
Arch == llvm::Triple::armeb28
||
476
28
        Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
477
3
      CmdArgs.push_back("-Bstatic");
478
28
    else
479
28
      CmdArgs.push_back("-static");
480
1.49k
  } else if (Args.hasArg(options::OPT_shared)) {
481
61
    CmdArgs.push_back("-shared");
482
61
  }
483
484
1.53k
  if (!IsStatic) {
485
1.49k
    if (Args.hasArg(options::OPT_rdynamic))
486
5
      CmdArgs.push_back("-export-dynamic");
487
488
1.49k
    if (!Args.hasArg(options::OPT_shared) && 
!IsStaticPIE1.43k
) {
489
1.43k
      CmdArgs.push_back("-dynamic-linker");
490
1.43k
      CmdArgs.push_back(Args.MakeArgString(Twine(D.DyldPrefix) +
491
1.43k
                                           ToolChain.getDynamicLinker(Args)));
492
1.43k
    }
493
1.49k
  }
494
495
1.53k
  CmdArgs.push_back("-o");
496
1.53k
  CmdArgs.push_back(Output.getFilename());
497
498
1.53k
  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
499
1.52k
    if (!isAndroid && 
!IsIAMCU1.35k
) {
500
1.35k
      const char *crt1 = nullptr;
501
1.35k
      if (!Args.hasArg(options::OPT_shared)) {
502
1.31k
        if (Args.hasArg(options::OPT_pg))
503
1
          crt1 = "gcrt1.o";
504
1.30k
        else if (IsPIE)
505
106
          crt1 = "Scrt1.o";
506
1.20k
        else if (IsStaticPIE)
507
4
          crt1 = "rcrt1.o";
508
1.19k
        else
509
1.19k
          crt1 = "crt1.o";
510
1.31k
      }
511
1.35k
      if (crt1)
512
1.31k
        CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
513
514
1.35k
      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
515
1.35k
    }
516
517
1.52k
    if (IsVE) {
518
0
      CmdArgs.push_back("-z");
519
0
      CmdArgs.push_back("max-page-size=0x4000000");
520
0
    }
521
522
1.52k
    if (IsIAMCU)
523
8
      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
524
1.51k
    else if (HasCRTBeginEndFiles) {
525
1.51k
      std::string P;
526
1.51k
      if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
527
12
          !isAndroid) {
528
9
        std::string crtbegin = ToolChain.getCompilerRT(Args, "crtbegin",
529
9
                                                       ToolChain::FT_Object);
530
9
        if (ToolChain.getVFS().exists(crtbegin))
531
2
          P = crtbegin;
532
9
      }
533
1.51k
      if (P.empty()) {
534
1.51k
        const char *crtbegin;
535
1.51k
        if (IsStatic)
536
23
          crtbegin = isAndroid ? 
"crtbegin_static.o"10
:
"crtbeginT.o"13
;
537
1.48k
        else if (Args.hasArg(options::OPT_shared))
538
61
          crtbegin = isAndroid ? 
"crtbegin_so.o"20
:
"crtbeginS.o"41
;
539
1.42k
        else if (IsPIE || 
IsStaticPIE1.24k
)
540
189
          crtbegin = isAndroid ? 
"crtbegin_dynamic.o"79
:
"crtbeginS.o"110
;
541
1.23k
        else
542
1.23k
          crtbegin = isAndroid ? 
"crtbegin_dynamic.o"54
:
"crtbegin.o"1.18k
;
543
1.51k
        P = ToolChain.GetFilePath(crtbegin);
544
1.51k
      }
545
1.51k
      CmdArgs.push_back(Args.MakeArgString(P));
546
1.51k
    }
547
548
    // Add crtfastmath.o if available and fast math is enabled.
549
1.52k
    ToolChain.addFastMathRuntimeIfAvailable(Args, CmdArgs);
550
1.52k
  }
551
552
1.53k
  Args.AddAllArgs(CmdArgs, options::OPT_L);
553
1.53k
  Args.AddAllArgs(CmdArgs, options::OPT_u);
554
555
1.53k
  ToolChain.AddFilePathLibArgs(Args, CmdArgs);
556
557
1.53k
  if (D.isUsingLTO()) {
558
63
    assert(!Inputs.empty() && "Must have at least one input.");
559
63
    addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
560
63
                  D.getLTOMode() == LTOK_Thin);
561
63
  }
562
563
1.53k
  if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
564
1
    CmdArgs.push_back("--no-demangle");
565
566
1.53k
  bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
567
1.53k
  bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
568
1.53k
  addLinkerCompressDebugSectionsOption(ToolChain, Args, CmdArgs);
569
1.53k
  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
570
  // The profile runtime also needs access to system libraries.
571
1.53k
  getToolChain().addProfileRTLibs(Args, CmdArgs);
572
573
1.53k
  if (D.CCCIsCXX() &&
574
25
      !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
575
25
    if (ToolChain.ShouldLinkCXXStdlib(Args)) {
576
23
      bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
577
0
                                 !Args.hasArg(options::OPT_static);
578
23
      if (OnlyLibstdcxxStatic)
579
0
        CmdArgs.push_back("-Bstatic");
580
23
      ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
581
23
      if (OnlyLibstdcxxStatic)
582
0
        CmdArgs.push_back("-Bdynamic");
583
23
    }
584
25
    CmdArgs.push_back("-lm");
585
25
  }
586
  // Silence warnings when linking C code with a C++ '-stdlib' argument.
587
1.53k
  Args.ClaimAllArgs(options::OPT_stdlib_EQ);
588
589
1.53k
  if (!Args.hasArg(options::OPT_nostdlib)) {
590
1.52k
    if (!Args.hasArg(options::OPT_nodefaultlibs)) {
591
1.52k
      if (IsStatic || 
IsStaticPIE1.48k
)
592
35
        CmdArgs.push_back("--start-group");
593
594
1.52k
      if (NeedsSanitizerDeps)
595
275
        linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
596
597
1.52k
      if (NeedsXRayDeps)
598
0
        linkXRayRuntimeDeps(ToolChain, CmdArgs);
599
600
1.52k
      bool WantPthread = Args.hasArg(options::OPT_pthread) ||
601
1.50k
                         Args.hasArg(options::OPT_pthreads);
602
603
      // Use the static OpenMP runtime with -static-openmp
604
1.52k
      bool StaticOpenMP = Args.hasArg(options::OPT_static_openmp) &&
605
4
                          !Args.hasArg(options::OPT_static);
606
607
      // FIXME: Only pass GompNeedsRT = true for platforms with libgomp that
608
      // require librt. Most modern Linux platforms do, but some may not.
609
1.52k
      if (addOpenMPRuntime(CmdArgs, ToolChain, Args, StaticOpenMP,
610
1.52k
                           JA.isHostOffloading(Action::OFK_OpenMP),
611
1.52k
                           /* GompNeedsRT= */ true))
612
        // OpenMP runtimes implies pthreads when using the GNU toolchain.
613
        // FIXME: Does this really make sense for all GNU toolchains?
614
57
        WantPthread = true;
615
616
1.52k
      AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
617
618
1.52k
      if (WantPthread && 
!isAndroid73
)
619
57
        CmdArgs.push_back("-lpthread");
620
621
1.52k
      if (Args.hasArg(options::OPT_fsplit_stack))
622
2
        CmdArgs.push_back("--wrap=pthread_create");
623
624
1.52k
      if (!Args.hasArg(options::OPT_nolibc))
625
1.51k
        CmdArgs.push_back("-lc");
626
627
      // Add IAMCU specific libs, if needed.
628
1.52k
      if (IsIAMCU)
629
8
        CmdArgs.push_back("-lgloss");
630
631
1.52k
      if (IsStatic || 
IsStaticPIE1.48k
)
632
35
        CmdArgs.push_back("--end-group");
633
1.48k
      else
634
1.48k
        AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
635
636
      // Add IAMCU specific libs (outside the group), if needed.
637
1.52k
      if (IsIAMCU) {
638
8
        CmdArgs.push_back("--as-needed");
639
8
        CmdArgs.push_back("-lsoftfp");
640
8
        CmdArgs.push_back("--no-as-needed");
641
8
      }
642
1.52k
    }
643
644
1.52k
    if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
645
1.51k
      if (HasCRTBeginEndFiles) {
646
1.51k
        std::string P;
647
1.51k
        if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
648
12
            !isAndroid) {
649
9
          std::string crtend = ToolChain.getCompilerRT(Args, "crtend",
650
9
                                                       ToolChain::FT_Object);
651
9
          if (ToolChain.getVFS().exists(crtend))
652
2
            P = crtend;
653
9
        }
654
1.51k
        if (P.empty()) {
655
1.51k
          const char *crtend;
656
1.51k
          if (Args.hasArg(options::OPT_shared))
657
61
            crtend = isAndroid ? 
"crtend_so.o"20
:
"crtendS.o"41
;
658
1.44k
          else if (IsPIE || 
IsStaticPIE1.26k
)
659
189
            crtend = isAndroid ? 
"crtend_android.o"79
:
"crtendS.o"110
;
660
1.26k
          else
661
1.26k
            crtend = isAndroid ? 
"crtend_android.o"64
:
"crtend.o"1.19k
;
662
1.51k
          P = ToolChain.GetFilePath(crtend);
663
1.51k
        }
664
1.51k
        CmdArgs.push_back(Args.MakeArgString(P));
665
1.51k
      }
666
1.51k
      if (!isAndroid)
667
1.35k
        CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
668
1.51k
    }
669
1.52k
  }
670
671
1.53k
  Args.AddAllArgs(CmdArgs, options::OPT_T);
672
673
1.53k
  const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
674
1.53k
  C.addCommand(std::make_unique<Command>(JA, *this,
675
1.53k
                                         ResponseFileSupport::AtFileCurCP(),
676
1.53k
                                         Exec, CmdArgs, Inputs, Output));
677
1.53k
}
678
679
void tools::gnutools::Assembler::ConstructJob(Compilation &C,
680
                                              const JobAction &JA,
681
                                              const InputInfo &Output,
682
                                              const InputInfoList &Inputs,
683
                                              const ArgList &Args,
684
357
                                              const char *LinkingOutput) const {
685
357
  const auto &D = getToolChain().getDriver();
686
687
357
  claimNoWarnArgs(Args);
688
689
357
  ArgStringList CmdArgs;
690
691
357
  llvm::Reloc::Model RelocationModel;
692
357
  unsigned PICLevel;
693
357
  bool IsPIE;
694
357
  const char *DefaultAssembler = "as";
695
357
  std::tie(RelocationModel, PICLevel, IsPIE) =
696
357
      ParsePICArgs(getToolChain(), Args);
697
698
357
  if (const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ)) {
699
10
    if (A->getOption().getID() == options::OPT_gz) {
700
0
      CmdArgs.push_back("--compress-debug-sections");
701
10
    } else {
702
10
      StringRef Value = A->getValue();
703
10
      if (Value == "none" || 
Value == "zlib"8
||
Value == "zlib-gnu"4
) {
704
8
        CmdArgs.push_back(
705
8
            Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
706
2
      } else {
707
2
        D.Diag(diag::err_drv_unsupported_option_argument)
708
2
            << A->getOption().getName() << Value;
709
2
      }
710
10
    }
711
10
  }
712
713
357
  if (getToolChain().isNoExecStackDefault()) {
714
2
      CmdArgs.push_back("--noexecstack");
715
2
  }
716
717
357
  switch (getToolChain().getArch()) {
718
105
  default:
719
105
    break;
720
  // Add --32/--64 to make sure we get the format we want.
721
  // This is incomplete
722
25
  case llvm::Triple::x86:
723
25
    CmdArgs.push_back("--32");
724
25
    break;
725
19
  case llvm::Triple::x86_64:
726
19
    if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
727
1
      CmdArgs.push_back("--x32");
728
18
    else
729
18
      CmdArgs.push_back("--64");
730
19
    break;
731
5
  case llvm::Triple::ppc: {
732
5
    CmdArgs.push_back("-a32");
733
5
    CmdArgs.push_back("-mppc");
734
5
    CmdArgs.push_back("-mbig-endian");
735
5
    CmdArgs.push_back(
736
5
      ppc::getPPCAsmModeForCPU(getCPUName(Args, getToolChain().getTriple())));
737
5
    break;
738
0
  }
739
1
  case llvm::Triple::ppcle: {
740
1
    CmdArgs.push_back("-a32");
741
1
    CmdArgs.push_back("-mppc");
742
1
    CmdArgs.push_back("-mlittle-endian");
743
1
    CmdArgs.push_back(
744
1
        ppc::getPPCAsmModeForCPU(getCPUName(Args, getToolChain().getTriple())));
745
1
    break;
746
0
  }
747
4
  case llvm::Triple::ppc64: {
748
4
    CmdArgs.push_back("-a64");
749
4
    CmdArgs.push_back("-mppc64");
750
4
    CmdArgs.push_back("-mbig-endian");
751
4
    CmdArgs.push_back(
752
4
      ppc::getPPCAsmModeForCPU(getCPUName(Args, getToolChain().getTriple())));
753
4
    break;
754
0
  }
755
2
  case llvm::Triple::ppc64le: {
756
2
    CmdArgs.push_back("-a64");
757
2
    CmdArgs.push_back("-mppc64");
758
2
    CmdArgs.push_back("-mlittle-endian");
759
2
    CmdArgs.push_back(
760
2
      ppc::getPPCAsmModeForCPU(getCPUName(Args, getToolChain().getTriple())));
761
2
    break;
762
0
  }
763
3
  case llvm::Triple::riscv32:
764
6
  case llvm::Triple::riscv64: {
765
6
    StringRef ABIName = riscv::getRISCVABI(Args, getToolChain().getTriple());
766
6
    CmdArgs.push_back("-mabi");
767
6
    CmdArgs.push_back(ABIName.data());
768
6
    StringRef MArchName = riscv::getRISCVArch(Args, getToolChain().getTriple());
769
6
    CmdArgs.push_back("-march");
770
6
    CmdArgs.push_back(MArchName.data());
771
6
    break;
772
3
  }
773
41
  case llvm::Triple::sparc:
774
45
  case llvm::Triple::sparcel: {
775
45
    CmdArgs.push_back("-32");
776
45
    std::string CPU = getCPUName(Args, getToolChain().getTriple());
777
45
    CmdArgs.push_back(
778
45
        sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
779
45
    AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
780
45
    break;
781
41
  }
782
13
  case llvm::Triple::sparcv9: {
783
13
    CmdArgs.push_back("-64");
784
13
    std::string CPU = getCPUName(Args, getToolChain().getTriple());
785
13
    CmdArgs.push_back(
786
13
        sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
787
13
    AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
788
13
    break;
789
41
  }
790
21
  case llvm::Triple::arm:
791
26
  case llvm::Triple::armeb:
792
30
  case llvm::Triple::thumb:
793
34
  case llvm::Triple::thumbeb: {
794
34
    const llvm::Triple &Triple2 = getToolChain().getTriple();
795
26
    CmdArgs.push_back(isArmBigEndian(Triple2, Args) ? 
"-EB"8
: "-EL");
796
34
    switch (Triple2.getSubArch()) {
797
8
    case llvm::Triple::ARMSubArch_v7:
798
8
      CmdArgs.push_back("-mfpu=neon");
799
8
      break;
800
4
    case llvm::Triple::ARMSubArch_v8:
801
4
      CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
802
4
      break;
803
22
    default:
804
22
      break;
805
34
    }
806
807
34
    switch (arm::getARMFloatABI(getToolChain(), Args)) {
808
0
    case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
809
24
    case arm::FloatABI::Soft:
810
24
      CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
811
24
      break;
812
2
    case arm::FloatABI::SoftFP:
813
2
      CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
814
2
      break;
815
8
    case arm::FloatABI::Hard:
816
8
      CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
817
8
      break;
818
34
    }
819
820
34
    Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
821
34
    normalizeCPUNamesForAssembler(Args, CmdArgs);
822
823
34
    Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
824
34
    break;
825
34
  }
826
6
  case llvm::Triple::aarch64:
827
10
  case llvm::Triple::aarch64_be: {
828
10
    CmdArgs.push_back(
829
6
        getToolChain().getArch() == llvm::Triple::aarch64_be ? 
"-EB"4
: "-EL");
830
10
    Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
831
10
    normalizeCPUNamesForAssembler(Args, CmdArgs);
832
833
10
    break;
834
6
  }
835
53
  case llvm::Triple::mips:
836
57
  case llvm::Triple::mipsel:
837
80
  case llvm::Triple::mips64:
838
85
  case llvm::Triple::mips64el: {
839
85
    StringRef CPUName;
840
85
    StringRef ABIName;
841
85
    mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
842
85
    ABIName = mips::getGnuCompatibleMipsABIName(ABIName);
843
844
85
    CmdArgs.push_back("-march");
845
85
    CmdArgs.push_back(CPUName.data());
846
847
85
    CmdArgs.push_back("-mabi");
848
85
    CmdArgs.push_back(ABIName.data());
849
850
    // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
851
    // or -mshared (not implemented) is in effect.
852
85
    if (RelocationModel == llvm::Reloc::Static)
853
66
      CmdArgs.push_back("-mno-shared");
854
855
    // LLVM doesn't support -mplt yet and acts as if it is always given.
856
    // However, -mplt has no effect with the N64 ABI.
857
85
    if (ABIName != "64" && 
!Args.hasArg(options::OPT_mno_abicalls)59
)
858
59
      CmdArgs.push_back("-call_nonpic");
859
860
85
    if (getToolChain().getTriple().isLittleEndian())
861
9
      CmdArgs.push_back("-EL");
862
76
    else
863
76
      CmdArgs.push_back("-EB");
864
865
85
    if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
866
2
      if (StringRef(A->getValue()) == "2008")
867
1
        CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
868
2
    }
869
870
    // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
871
85
    if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
872
9
                                 options::OPT_mfp64)) {
873
9
      A->claim();
874
9
      A->render(Args, CmdArgs);
875
76
    } else if (mips::shouldUseFPXX(
876
76
                   Args, getToolChain().getTriple(), CPUName, ABIName,
877
76
                   mips::getMipsFloatABI(getToolChain().getDriver(), Args,
878
76
                                         getToolChain().getTriple())))
879
0
      CmdArgs.push_back("-mfpxx");
880
881
    // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
882
    // -mno-mips16 is actually -no-mips16.
883
85
    if (Arg *A =
884
2
            Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
885
2
      if (A->getOption().matches(options::OPT_mips16)) {
886
1
        A->claim();
887
1
        A->render(Args, CmdArgs);
888
1
      } else {
889
1
        A->claim();
890
1
        CmdArgs.push_back("-no-mips16");
891
1
      }
892
2
    }
893
894
85
    Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
895
85
                    options::OPT_mno_micromips);
896
85
    Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
897
85
    Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
898
899
85
    if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
900
      // Do not use AddLastArg because not all versions of MIPS assembler
901
      // support -mmsa / -mno-msa options.
902
2
      if (A->getOption().matches(options::OPT_mmsa))
903
1
        CmdArgs.push_back(Args.MakeArgString("-mmsa"));
904
2
    }
905
906
85
    Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
907
85
                    options::OPT_msoft_float);
908
909
85
    Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
910
85
                    options::OPT_msingle_float);
911
912
85
    Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
913
85
                    options::OPT_mno_odd_spreg);
914
915
85
    AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
916
85
    break;
917
80
  }
918
3
  case llvm::Triple::systemz: {
919
    // Always pass an -march option, since our default of z10 is later
920
    // than the GNU assembler's default.
921
3
    std::string CPUName = systemz::getSystemZTargetCPU(Args);
922
3
    CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
923
3
    break;
924
80
  }
925
0
  case llvm::Triple::ve:
926
0
    DefaultAssembler = "nas";
927
357
  }
928
929
357
  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
930
0
                                    options::OPT_fdebug_prefix_map_EQ)) {
931
0
    StringRef Map = A->getValue();
932
0
    if (Map.find('=') == StringRef::npos)
933
0
      D.Diag(diag::err_drv_invalid_argument_to_option)
934
0
          << Map << A->getOption().getName();
935
0
    else {
936
0
      CmdArgs.push_back(Args.MakeArgString("--debug-prefix-map"));
937
0
      CmdArgs.push_back(Args.MakeArgString(Map));
938
0
    }
939
0
    A->claim();
940
0
  }
941
942
357
  Args.AddAllArgs(CmdArgs, options::OPT_I);
943
357
  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
944
945
357
  CmdArgs.push_back("-o");
946
357
  CmdArgs.push_back(Output.getFilename());
947
948
357
  for (const auto &II : Inputs)
949
362
    CmdArgs.push_back(II.getFilename());
950
951
357
  const char *Exec =
952
357
      Args.MakeArgString(getToolChain().GetProgramPath(DefaultAssembler));
953
357
  C.addCommand(std::make_unique<Command>(JA, *this,
954
357
                                         ResponseFileSupport::AtFileCurCP(),
955
357
                                         Exec, CmdArgs, Inputs, Output));
956
957
  // Handle the debug info splitting at object creation time if we're
958
  // creating an object.
959
  // TODO: Currently only works on linux with newer objcopy.
960
357
  if (Args.hasArg(options::OPT_gsplit_dwarf) &&
961
1
      getToolChain().getTriple().isOSLinux())
962
1
    SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
963
1
                   SplitDebugName(JA, Args, Inputs[0], Output));
964
357
}
965
966
namespace {
967
// Filter to remove Multilibs that don't exist as a suffix to Path
968
class FilterNonExistent {
969
  StringRef Base, File;
970
  llvm::vfs::FileSystem &VFS;
971
972
public:
973
  FilterNonExistent(StringRef Base, StringRef File, llvm::vfs::FileSystem &VFS)
974
530
      : Base(Base), File(File), VFS(VFS) {}
975
23.7k
  bool operator()(const Multilib &M) {
976
23.7k
    return !VFS.exists(Base + M.gccSuffix() + File);
977
23.7k
  }
978
};
979
} // end anonymous namespace
980
981
370
static bool isSoftFloatABI(const ArgList &Args) {
982
370
  Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
983
370
                           options::OPT_mfloat_abi_EQ);
984
370
  if (!A)
985
162
    return false;
986
987
208
  return A->getOption().matches(options::OPT_msoft_float) ||
988
138
         (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
989
4
          A->getValue() == StringRef("soft"));
990
208
}
991
992
528
static bool isArmOrThumbArch(llvm::Triple::ArchType Arch) {
993
528
  return Arch == llvm::Triple::arm || 
Arch == llvm::Triple::thumb495
;
994
528
}
995
996
370
static bool isMipsEL(llvm::Triple::ArchType Arch) {
997
370
  return Arch == llvm::Triple::mipsel || 
Arch == llvm::Triple::mips64el252
;
998
370
}
999
1000
185
static bool isMips16(const ArgList &Args) {
1001
185
  Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
1002
185
  return A && 
A->getOption().matches(options::OPT_mips16)24
;
1003
185
}
1004
1005
185
static bool isMicroMips(const ArgList &Args) {
1006
185
  Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
1007
185
  return A && 
A->getOption().matches(options::OPT_mmicromips)20
;
1008
185
}
1009
1010
291
static bool isMSP430(llvm::Triple::ArchType Arch) {
1011
291
  return Arch == llvm::Triple::msp430;
1012
291
}
1013
1014
4.24k
static Multilib makeMultilib(StringRef commonSuffix) {
1015
4.24k
  return Multilib(commonSuffix, commonSuffix, commonSuffix);
1016
4.24k
}
1017
1018
static bool findMipsCsMultilibs(const Multilib::flags_list &Flags,
1019
                                FilterNonExistent &NonExistent,
1020
41
                                DetectedMultilibs &Result) {
1021
  // Check for Code Sourcery toolchain multilibs
1022
41
  MultilibSet CSMipsMultilibs;
1023
41
  {
1024
41
    auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
1025
1026
41
    auto MArchMicroMips =
1027
41
        makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
1028
1029
41
    auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
1030
1031
41
    auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1032
1033
41
    auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
1034
1035
41
    auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1036
1037
41
    auto DefaultFloat =
1038
41
        makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
1039
1040
41
    auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1041
1042
41
    auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1043
1044
    // Note that this one's osSuffix is ""
1045
41
    auto MAbi64 = makeMultilib("")
1046
41
                      .gccSuffix("/64")
1047
41
                      .includeSuffix("/64")
1048
41
                      .flag("+mabi=n64")
1049
41
                      .flag("-mabi=n32")
1050
41
                      .flag("-m32");
1051
1052
41
    CSMipsMultilibs =
1053
41
        MultilibSet()
1054
41
            .Either(MArchMips16, MArchMicroMips, MArchDefault)
1055
41
            .Maybe(UCLibc)
1056
41
            .Either(SoftFloat, Nan2008, DefaultFloat)
1057
41
            .FilterOut("/micromips/nan2008")
1058
41
            .FilterOut("/mips16/nan2008")
1059
41
            .Either(BigEndian, LittleEndian)
1060
41
            .Maybe(MAbi64)
1061
41
            .FilterOut("/mips16.*/64")
1062
41
            .FilterOut("/micromips.*/64")
1063
41
            .FilterOut(NonExistent)
1064
25
            .setIncludeDirsCallback([](const Multilib &M) {
1065
25
              std::vector<std::string> Dirs({"/include"});
1066
25
              if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1067
6
                Dirs.push_back(
1068
6
                    "/../../../../mips-linux-gnu/libc/uclibc/usr/include");
1069
19
              else
1070
19
                Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include");
1071
25
              return Dirs;
1072
25
            });
1073
41
  }
1074
1075
41
  MultilibSet DebianMipsMultilibs;
1076
41
  {
1077
41
    Multilib MAbiN32 =
1078
41
        Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
1079
1080
41
    Multilib M64 = Multilib()
1081
41
                       .gccSuffix("/64")
1082
41
                       .includeSuffix("/64")
1083
41
                       .flag("+m64")
1084
41
                       .flag("-m32")
1085
41
                       .flag("-mabi=n32");
1086
1087
41
    Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
1088
1089
41
    DebianMipsMultilibs =
1090
41
        MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
1091
41
  }
1092
1093
  // Sort candidates. Toolchain that best meets the directories tree goes first.
1094
  // Then select the first toolchains matches command line flags.
1095
41
  MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs};
1096
41
  if (CSMipsMultilibs.size() < DebianMipsMultilibs.size())
1097
9
    std::iter_swap(Candidates, Candidates + 1);
1098
48
  for (const MultilibSet *Candidate : Candidates) {
1099
48
    if (Candidate->select(Flags, Result.SelectedMultilib)) {
1100
35
      if (Candidate == &DebianMipsMultilibs)
1101
10
        Result.BiarchSibling = Multilib();
1102
35
      Result.Multilibs = *Candidate;
1103
35
      return true;
1104
35
    }
1105
48
  }
1106
6
  return false;
1107
41
}
1108
1109
static bool findMipsAndroidMultilibs(llvm::vfs::FileSystem &VFS, StringRef Path,
1110
                                     const Multilib::flags_list &Flags,
1111
                                     FilterNonExistent &NonExistent,
1112
4
                                     DetectedMultilibs &Result) {
1113
1114
4
  MultilibSet AndroidMipsMultilibs =
1115
4
      MultilibSet()
1116
4
          .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
1117
4
          .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
1118
4
          .FilterOut(NonExistent);
1119
1120
4
  MultilibSet AndroidMipselMultilibs =
1121
4
      MultilibSet()
1122
4
          .Either(Multilib().flag("+march=mips32"),
1123
4
                  Multilib("/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
1124
4
                  Multilib("/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
1125
4
          .FilterOut(NonExistent);
1126
1127
4
  MultilibSet AndroidMips64elMultilibs =
1128
4
      MultilibSet()
1129
4
          .Either(
1130
4
              Multilib().flag("+march=mips64r6"),
1131
4
              Multilib("/32/mips-r1", "", "/mips-r1").flag("+march=mips32"),
1132
4
              Multilib("/32/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
1133
4
              Multilib("/32/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
1134
4
          .FilterOut(NonExistent);
1135
1136
4
  MultilibSet *MS = &AndroidMipsMultilibs;
1137
4
  if (VFS.exists(Path + "/mips-r6"))
1138
1
    MS = &AndroidMipselMultilibs;
1139
3
  else if (VFS.exists(Path + "/32"))
1140
0
    MS = &AndroidMips64elMultilibs;
1141
4
  if (MS->select(Flags, Result.SelectedMultilib)) {
1142
4
    Result.Multilibs = *MS;
1143
4
    return true;
1144
4
  }
1145
0
  return false;
1146
0
}
1147
1148
static bool findMipsMuslMultilibs(const Multilib::flags_list &Flags,
1149
                                  FilterNonExistent &NonExistent,
1150
2
                                  DetectedMultilibs &Result) {
1151
  // Musl toolchain multilibs
1152
2
  MultilibSet MuslMipsMultilibs;
1153
2
  {
1154
2
    auto MArchMipsR2 = makeMultilib("")
1155
2
                           .osSuffix("/mips-r2-hard-musl")
1156
2
                           .flag("+EB")
1157
2
                           .flag("-EL")
1158
2
                           .flag("+march=mips32r2");
1159
1160
2
    auto MArchMipselR2 = makeMultilib("/mipsel-r2-hard-musl")
1161
2
                             .flag("-EB")
1162
2
                             .flag("+EL")
1163
2
                             .flag("+march=mips32r2");
1164
1165
2
    MuslMipsMultilibs = MultilibSet().Either(MArchMipsR2, MArchMipselR2);
1166
1167
    // Specify the callback that computes the include directories.
1168
2
    MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) {
1169
2
      return std::vector<std::string>(
1170
2
          {"/../sysroot" + M.osSuffix() + "/usr/include"});
1171
2
    });
1172
2
  }
1173
2
  if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
1174
2
    Result.Multilibs = MuslMipsMultilibs;
1175
2
    return true;
1176
2
  }
1177
0
  return false;
1178
0
}
1179
1180
static bool findMipsMtiMultilibs(const Multilib::flags_list &Flags,
1181
                                 FilterNonExistent &NonExistent,
1182
120
                                 DetectedMultilibs &Result) {
1183
  // CodeScape MTI toolchain v1.2 and early.
1184
120
  MultilibSet MtiMipsMultilibsV1;
1185
120
  {
1186
120
    auto MArchMips32 = makeMultilib("/mips32")
1187
120
                           .flag("+m32")
1188
120
                           .flag("-m64")
1189
120
                           .flag("-mmicromips")
1190
120
                           .flag("+march=mips32");
1191
1192
120
    auto MArchMicroMips = makeMultilib("/micromips")
1193
120
                              .flag("+m32")
1194
120
                              .flag("-m64")
1195
120
                              .flag("+mmicromips");
1196
1197
120
    auto MArchMips64r2 = makeMultilib("/mips64r2")
1198
120
                             .flag("-m32")
1199
120
                             .flag("+m64")
1200
120
                             .flag("+march=mips64r2");
1201
1202
120
    auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
1203
120
        "-march=mips64r2");
1204
1205
120
    auto MArchDefault = makeMultilib("")
1206
120
                            .flag("+m32")
1207
120
                            .flag("-m64")
1208
120
                            .flag("-mmicromips")
1209
120
                            .flag("+march=mips32r2");
1210
1211
120
    auto Mips16 = makeMultilib("/mips16").flag("+mips16");
1212
1213
120
    auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1214
1215
120
    auto MAbi64 =
1216
120
        makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1217
1218
120
    auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1219
1220
120
    auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1221
1222
120
    auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
1223
1224
120
    auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1225
1226
120
    MtiMipsMultilibsV1 =
1227
120
        MultilibSet()
1228
120
            .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1229
120
                    MArchDefault)
1230
120
            .Maybe(UCLibc)
1231
120
            .Maybe(Mips16)
1232
120
            .FilterOut("/mips64/mips16")
1233
120
            .FilterOut("/mips64r2/mips16")
1234
120
            .FilterOut("/micromips/mips16")
1235
120
            .Maybe(MAbi64)
1236
120
            .FilterOut("/micromips/64")
1237
120
            .FilterOut("/mips32/64")
1238
120
            .FilterOut("^/64")
1239
120
            .FilterOut("/mips16/64")
1240
120
            .Either(BigEndian, LittleEndian)
1241
120
            .Maybe(SoftFloat)
1242
120
            .Maybe(Nan2008)
1243
120
            .FilterOut(".*sof/nan2008")
1244
120
            .FilterOut(NonExistent)
1245
104
            .setIncludeDirsCallback([](const Multilib &M) {
1246
104
              std::vector<std::string> Dirs({"/include"});
1247
104
              if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1248
6
                Dirs.push_back("/../../../../sysroot/uclibc/usr/include");
1249
98
              else
1250
98
                Dirs.push_back("/../../../../sysroot/usr/include");
1251
104
              return Dirs;
1252
104
            });
1253
120
  }
1254
1255
  // CodeScape IMG toolchain starting from v1.3.
1256
120
  MultilibSet MtiMipsMultilibsV2;
1257
120
  {
1258
120
    auto BeHard = makeMultilib("/mips-r2-hard")
1259
120
                      .flag("+EB")
1260
120
                      .flag("-msoft-float")
1261
120
                      .flag("-mnan=2008")
1262
120
                      .flag("-muclibc");
1263
120
    auto BeSoft = makeMultilib("/mips-r2-soft")
1264
120
                      .flag("+EB")
1265
120
                      .flag("+msoft-float")
1266
120
                      .flag("-mnan=2008");
1267
120
    auto ElHard = makeMultilib("/mipsel-r2-hard")
1268
120
                      .flag("+EL")
1269
120
                      .flag("-msoft-float")
1270
120
                      .flag("-mnan=2008")
1271
120
                      .flag("-muclibc");
1272
120
    auto ElSoft = makeMultilib("/mipsel-r2-soft")
1273
120
                      .flag("+EL")
1274
120
                      .flag("+msoft-float")
1275
120
                      .flag("-mnan=2008")
1276
120
                      .flag("-mmicromips");
1277
120
    auto BeHardNan = makeMultilib("/mips-r2-hard-nan2008")
1278
120
                         .flag("+EB")
1279
120
                         .flag("-msoft-float")
1280
120
                         .flag("+mnan=2008")
1281
120
                         .flag("-muclibc");
1282
120
    auto ElHardNan = makeMultilib("/mipsel-r2-hard-nan2008")
1283
120
                         .flag("+EL")
1284
120
                         .flag("-msoft-float")
1285
120
                         .flag("+mnan=2008")
1286
120
                         .flag("-muclibc")
1287
120
                         .flag("-mmicromips");
1288
120
    auto BeHardNanUclibc = makeMultilib("/mips-r2-hard-nan2008-uclibc")
1289
120
                               .flag("+EB")
1290
120
                               .flag("-msoft-float")
1291
120
                               .flag("+mnan=2008")
1292
120
                               .flag("+muclibc");
1293
120
    auto ElHardNanUclibc = makeMultilib("/mipsel-r2-hard-nan2008-uclibc")
1294
120
                               .flag("+EL")
1295
120
                               .flag("-msoft-float")
1296
120
                               .flag("+mnan=2008")
1297
120
                               .flag("+muclibc");
1298
120
    auto BeHardUclibc = makeMultilib("/mips-r2-hard-uclibc")
1299
120
                            .flag("+EB")
1300
120
                            .flag("-msoft-float")
1301
120
                            .flag("-mnan=2008")
1302
120
                            .flag("+muclibc");
1303
120
    auto ElHardUclibc = makeMultilib("/mipsel-r2-hard-uclibc")
1304
120
                            .flag("+EL")
1305
120
                            .flag("-msoft-float")
1306
120
                            .flag("-mnan=2008")
1307
120
                            .flag("+muclibc");
1308
120
    auto ElMicroHardNan = makeMultilib("/micromipsel-r2-hard-nan2008")
1309
120
                              .flag("+EL")
1310
120
                              .flag("-msoft-float")
1311
120
                              .flag("+mnan=2008")
1312
120
                              .flag("+mmicromips");
1313
120
    auto ElMicroSoft = makeMultilib("/micromipsel-r2-soft")
1314
120
                           .flag("+EL")
1315
120
                           .flag("+msoft-float")
1316
120
                           .flag("-mnan=2008")
1317
120
                           .flag("+mmicromips");
1318
1319
120
    auto O32 =
1320
120
        makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
1321
120
    auto N32 =
1322
120
        makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
1323
120
    auto N64 =
1324
120
        makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
1325
1326
120
    MtiMipsMultilibsV2 =
1327
120
        MultilibSet()
1328
120
            .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan,
1329
120
                     BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc,
1330
120
                     ElHardUclibc, ElMicroHardNan, ElMicroSoft})
1331
120
            .Either(O32, N32, N64)
1332
120
            .FilterOut(NonExistent)
1333
16
            .setIncludeDirsCallback([](const Multilib &M) {
1334
16
              return std::vector<std::string>({"/../../../../sysroot" +
1335
16
                                               M.includeSuffix() +
1336
16
                                               "/../usr/include"});
1337
16
            })
1338
16
            .setFilePathsCallback([](const Multilib &M) {
1339
16
              return std::vector<std::string>(
1340
16
                  {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()});
1341
16
            });
1342
120
  }
1343
136
  for (auto Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) {
1344
136
    if (Candidate->select(Flags, Result.SelectedMultilib)) {
1345
120
      Result.Multilibs = *Candidate;
1346
120
      return true;
1347
120
    }
1348
136
  }
1349
0
  return false;
1350
120
}
1351
1352
static bool findMipsImgMultilibs(const Multilib::flags_list &Flags,
1353
                                 FilterNonExistent &NonExistent,
1354
18
                                 DetectedMultilibs &Result) {
1355
  // CodeScape IMG toolchain v1.2 and early.
1356
18
  MultilibSet ImgMultilibsV1;
1357
18
  {
1358
18
    auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
1359
1360
18
    auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1361
1362
18
    auto MAbi64 =
1363
18
        makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1364
1365
18
    ImgMultilibsV1 =
1366
18
        MultilibSet()
1367
18
            .Maybe(Mips64r6)
1368
18
            .Maybe(MAbi64)
1369
18
            .Maybe(LittleEndian)
1370
18
            .FilterOut(NonExistent)
1371
6
            .setIncludeDirsCallback([](const Multilib &M) {
1372
6
              return std::vector<std::string>(
1373
6
                  {"/include", "/../../../../sysroot/usr/include"});
1374
6
            });
1375
18
  }
1376
1377
  // CodeScape IMG toolchain starting from v1.3.
1378
18
  MultilibSet ImgMultilibsV2;
1379
18
  {
1380
18
    auto BeHard = makeMultilib("/mips-r6-hard")
1381
18
                      .flag("+EB")
1382
18
                      .flag("-msoft-float")
1383
18
                      .flag("-mmicromips");
1384
18
    auto BeSoft = makeMultilib("/mips-r6-soft")
1385
18
                      .flag("+EB")
1386
18
                      .flag("+msoft-float")
1387
18
                      .flag("-mmicromips");
1388
18
    auto ElHard = makeMultilib("/mipsel-r6-hard")
1389
18
                      .flag("+EL")
1390
18
                      .flag("-msoft-float")
1391
18
                      .flag("-mmicromips");
1392
18
    auto ElSoft = makeMultilib("/mipsel-r6-soft")
1393
18
                      .flag("+EL")
1394
18
                      .flag("+msoft-float")
1395
18
                      .flag("-mmicromips");
1396
18
    auto BeMicroHard = makeMultilib("/micromips-r6-hard")
1397
18
                           .flag("+EB")
1398
18
                           .flag("-msoft-float")
1399
18
                           .flag("+mmicromips");
1400
18
    auto BeMicroSoft = makeMultilib("/micromips-r6-soft")
1401
18
                           .flag("+EB")
1402
18
                           .flag("+msoft-float")
1403
18
                           .flag("+mmicromips");
1404
18
    auto ElMicroHard = makeMultilib("/micromipsel-r6-hard")
1405
18
                           .flag("+EL")
1406
18
                           .flag("-msoft-float")
1407
18
                           .flag("+mmicromips");
1408
18
    auto ElMicroSoft = makeMultilib("/micromipsel-r6-soft")
1409
18
                           .flag("+EL")
1410
18
                           .flag("+msoft-float")
1411
18
                           .flag("+mmicromips");
1412
1413
18
    auto O32 =
1414
18
        makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
1415
18
    auto N32 =
1416
18
        makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
1417
18
    auto N64 =
1418
18
        makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
1419
1420
18
    ImgMultilibsV2 =
1421
18
        MultilibSet()
1422
18
            .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft,
1423
18
                     ElMicroHard, ElMicroSoft})
1424
18
            .Either(O32, N32, N64)
1425
18
            .FilterOut(NonExistent)
1426
12
            .setIncludeDirsCallback([](const Multilib &M) {
1427
12
              return std::vector<std::string>({"/../../../../sysroot" +
1428
12
                                               M.includeSuffix() +
1429
12
                                               "/../usr/include"});
1430
12
            })
1431
12
            .setFilePathsCallback([](const Multilib &M) {
1432
12
              return std::vector<std::string>(
1433
12
                  {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()});
1434
12
            });
1435
18
  }
1436
30
  for (auto Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) {
1437
30
    if (Candidate->select(Flags, Result.SelectedMultilib)) {
1438
18
      Result.Multilibs = *Candidate;
1439
18
      return true;
1440
18
    }
1441
30
  }
1442
0
  return false;
1443
18
}
1444
1445
bool clang::driver::findMIPSMultilibs(const Driver &D,
1446
                                      const llvm::Triple &TargetTriple,
1447
                                      StringRef Path, const ArgList &Args,
1448
185
                                      DetectedMultilibs &Result) {
1449
185
  FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1450
1451
185
  StringRef CPUName;
1452
185
  StringRef ABIName;
1453
185
  tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1454
1455
185
  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1456
1457
185
  Multilib::flags_list Flags;
1458
185
  addMultilibFlag(TargetTriple.isMIPS32(), "m32", Flags);
1459
185
  addMultilibFlag(TargetTriple.isMIPS64(), "m64", Flags);
1460
185
  addMultilibFlag(isMips16(Args), "mips16", Flags);
1461
185
  addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
1462
185
  addMultilibFlag(CPUName == "mips32r2" || 
CPUName == "mips32r3"106
||
1463
105
                      CPUName == "mips32r5" || 
CPUName == "p5600"104
,
1464
185
                  "march=mips32r2", Flags);
1465
185
  addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
1466
185
  addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
1467
185
  addMultilibFlag(CPUName == "mips64r2" || 
CPUName == "mips64r3"143
||
1468
142
                      CPUName == "mips64r5" || 
CPUName == "octeon"141
||
1469
141
                      CPUName == "octeon+",
1470
185
                  "march=mips64r2", Flags);
1471
185
  addMultilibFlag(CPUName == "mips64r6", "march=mips64r6", Flags);
1472
185
  addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
1473
185
  addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
1474
185
  addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
1475
185
                  Flags);
1476
185
  addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
1477
185
  addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
1478
185
  addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
1479
185
  addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
1480
185
  addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
1481
185
  addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
1482
1483
185
  if (TargetTriple.isAndroid())
1484
4
    return findMipsAndroidMultilibs(D.getVFS(), Path, Flags, NonExistent,
1485
4
                                    Result);
1486
1487
181
  if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1488
122
      TargetTriple.getOS() == llvm::Triple::Linux &&
1489
122
      TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
1490
2
    return findMipsMuslMultilibs(Flags, NonExistent, Result);
1491
1492
179
  if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1493
120
      TargetTriple.getOS() == llvm::Triple::Linux &&
1494
120
      TargetTriple.isGNUEnvironment())
1495
120
    return findMipsMtiMultilibs(Flags, NonExistent, Result);
1496
1497
59
  if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1498
18
      TargetTriple.getOS() == llvm::Triple::Linux &&
1499
18
      TargetTriple.isGNUEnvironment())
1500
18
    return findMipsImgMultilibs(Flags, NonExistent, Result);
1501
1502
41
  if (findMipsCsMultilibs(Flags, NonExistent, Result))
1503
35
    return true;
1504
1505
  // Fallback to the regular toolchain-tree structure.
1506
6
  Multilib Default;
1507
6
  Result.Multilibs.push_back(Default);
1508
6
  Result.Multilibs.FilterOut(NonExistent);
1509
1510
6
  if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
1511
6
    Result.BiarchSibling = Multilib();
1512
6
    return true;
1513
6
  }
1514
1515
0
  return false;
1516
0
}
1517
1518
static void findAndroidArmMultilibs(const Driver &D,
1519
                                    const llvm::Triple &TargetTriple,
1520
                                    StringRef Path, const ArgList &Args,
1521
18
                                    DetectedMultilibs &Result) {
1522
  // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb.
1523
18
  FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1524
18
  Multilib ArmV7Multilib = makeMultilib("/armv7-a")
1525
18
                               .flag("+march=armv7-a")
1526
18
                               .flag("-mthumb");
1527
18
  Multilib ThumbMultilib = makeMultilib("/thumb")
1528
18
                               .flag("-march=armv7-a")
1529
18
                               .flag("+mthumb");
1530
18
  Multilib ArmV7ThumbMultilib = makeMultilib("/armv7-a/thumb")
1531
18
                               .flag("+march=armv7-a")
1532
18
                               .flag("+mthumb");
1533
18
  Multilib DefaultMultilib = makeMultilib("")
1534
18
                               .flag("-march=armv7-a")
1535
18
                               .flag("-mthumb");
1536
18
  MultilibSet AndroidArmMultilibs =
1537
18
      MultilibSet()
1538
18
          .Either(ThumbMultilib, ArmV7Multilib,
1539
18
                  ArmV7ThumbMultilib, DefaultMultilib)
1540
18
          .FilterOut(NonExistent);
1541
1542
18
  Multilib::flags_list Flags;
1543
18
  llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ);
1544
18
  bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm;
1545
18
  bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb;
1546
18
  bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7;
1547
18
  bool IsThumbMode = IsThumbArch ||
1548
18
      Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) ||
1549
13
      (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::ISAKind::THUMB);
1550
18
  bool IsArmV7Mode = (IsArmArch || 
IsThumbArch0
) &&
1551
18
      (llvm::ARM::parseArchVersion(Arch) == 7 ||
1552
13
       (IsArmArch && Arch == "" && IsV7SubArch));
1553
18
  addMultilibFlag(IsArmV7Mode, "march=armv7-a", Flags);
1554
18
  addMultilibFlag(IsThumbMode, "mthumb", Flags);
1555
1556
18
  if (AndroidArmMultilibs.select(Flags, Result.SelectedMultilib))
1557
18
    Result.Multilibs = AndroidArmMultilibs;
1558
18
}
1559
1560
static bool findMSP430Multilibs(const Driver &D,
1561
                                const llvm::Triple &TargetTriple,
1562
                                StringRef Path, const ArgList &Args,
1563
13
                                DetectedMultilibs &Result) {
1564
13
  FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1565
13
  Multilib WithoutExceptions = makeMultilib("/430").flag("-exceptions");
1566
13
  Multilib WithExceptions = makeMultilib("/430/exceptions").flag("+exceptions");
1567
1568
  // FIXME: when clang starts to support msp430x ISA additional logic
1569
  // to select between multilib must be implemented
1570
  // Multilib MSP430xMultilib = makeMultilib("/large");
1571
1572
13
  Result.Multilibs.push_back(WithoutExceptions);
1573
13
  Result.Multilibs.push_back(WithExceptions);
1574
13
  Result.Multilibs.FilterOut(NonExistent);
1575
1576
13
  Multilib::flags_list Flags;
1577
13
  addMultilibFlag(Args.hasFlag(options::OPT_fexceptions,
1578
13
                               options::OPT_fno_exceptions, false),
1579
13
                  "exceptions", Flags);
1580
13
  if (Result.Multilibs.select(Flags, Result.SelectedMultilib))
1581
13
    return true;
1582
1583
0
  return false;
1584
0
}
1585
1586
static void findRISCVBareMetalMultilibs(const Driver &D,
1587
                                        const llvm::Triple &TargetTriple,
1588
                                        StringRef Path, const ArgList &Args,
1589
27
                                        DetectedMultilibs &Result) {
1590
27
  FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1591
27
  struct RiscvMultilib {
1592
27
    StringRef march;
1593
27
    StringRef mabi;
1594
27
  };
1595
  // currently only support the set of multilibs like riscv-gnu-toolchain does.
1596
  // TODO: support MULTILIB_REUSE
1597
27
  constexpr RiscvMultilib RISCVMultilibSet[] = {
1598
27
      {"rv32i", "ilp32"},     {"rv32im", "ilp32"},     {"rv32iac", "ilp32"},
1599
27
      {"rv32imac", "ilp32"},  {"rv32imafc", "ilp32f"}, {"rv64imac", "lp64"},
1600
27
      {"rv64imafdc", "lp64d"}};
1601
1602
27
  std::vector<Multilib> Ms;
1603
189
  for (auto Element : RISCVMultilibSet) {
1604
    // multilib path rule is ${march}/${mabi}
1605
189
    Ms.emplace_back(
1606
189
        makeMultilib((Twine(Element.march) + "/" + Twine(Element.mabi)).str())
1607
189
            .flag(Twine("+march=", Element.march).str())
1608
189
            .flag(Twine("+mabi=", Element.mabi).str()));
1609
189
  }
1610
27
  MultilibSet RISCVMultilibs =
1611
27
      MultilibSet()
1612
27
          .Either(ArrayRef<Multilib>(Ms))
1613
27
          .FilterOut(NonExistent)
1614
11
          .setFilePathsCallback([](const Multilib &M) {
1615
11
            return std::vector<std::string>(
1616
11
                {M.gccSuffix(),
1617
11
                 "/../../../../riscv64-unknown-elf/lib" + M.gccSuffix(),
1618
11
                 "/../../../../riscv32-unknown-elf/lib" + M.gccSuffix()});
1619
11
          });
1620
1621
1622
27
  Multilib::flags_list Flags;
1623
27
  llvm::StringSet<> Added_ABIs;
1624
27
  StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1625
27
  StringRef MArch = tools::riscv::getRISCVArch(Args, TargetTriple);
1626
189
  for (auto Element : RISCVMultilibSet) {
1627
189
    addMultilibFlag(MArch == Element.march,
1628
189
                    Twine("march=", Element.march).str().c_str(), Flags);
1629
189
    if (!Added_ABIs.count(Element.mabi)) {
1630
108
      Added_ABIs.insert(Element.mabi);
1631
108
      addMultilibFlag(ABIName == Element.mabi,
1632
108
                      Twine("mabi=", Element.mabi).str().c_str(), Flags);
1633
108
    }
1634
189
  }
1635
1636
27
  if (RISCVMultilibs.select(Flags, Result.SelectedMultilib))
1637
11
    Result.Multilibs = RISCVMultilibs;
1638
27
}
1639
1640
static void findRISCVMultilibs(const Driver &D,
1641
                               const llvm::Triple &TargetTriple, StringRef Path,
1642
36
                               const ArgList &Args, DetectedMultilibs &Result) {
1643
36
  if (TargetTriple.getOS() == llvm::Triple::UnknownOS)
1644
27
    return findRISCVBareMetalMultilibs(D, TargetTriple, Path, Args, Result);
1645
1646
9
  FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1647
9
  Multilib Ilp32 = makeMultilib("lib32/ilp32").flag("+m32").flag("+mabi=ilp32");
1648
9
  Multilib Ilp32f =
1649
9
      makeMultilib("lib32/ilp32f").flag("+m32").flag("+mabi=ilp32f");
1650
9
  Multilib Ilp32d =
1651
9
      makeMultilib("lib32/ilp32d").flag("+m32").flag("+mabi=ilp32d");
1652
9
  Multilib Lp64 = makeMultilib("lib64/lp64").flag("+m64").flag("+mabi=lp64");
1653
9
  Multilib Lp64f = makeMultilib("lib64/lp64f").flag("+m64").flag("+mabi=lp64f");
1654
9
  Multilib Lp64d = makeMultilib("lib64/lp64d").flag("+m64").flag("+mabi=lp64d");
1655
9
  MultilibSet RISCVMultilibs =
1656
9
      MultilibSet()
1657
9
          .Either({Ilp32, Ilp32f, Ilp32d, Lp64, Lp64f, Lp64d})
1658
9
          .FilterOut(NonExistent);
1659
1660
9
  Multilib::flags_list Flags;
1661
9
  bool IsRV64 = TargetTriple.getArch() == llvm::Triple::riscv64;
1662
9
  StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1663
1664
9
  addMultilibFlag(!IsRV64, "m32", Flags);
1665
9
  addMultilibFlag(IsRV64, "m64", Flags);
1666
9
  addMultilibFlag(ABIName == "ilp32", "mabi=ilp32", Flags);
1667
9
  addMultilibFlag(ABIName == "ilp32f", "mabi=ilp32f", Flags);
1668
9
  addMultilibFlag(ABIName == "ilp32d", "mabi=ilp32d", Flags);
1669
9
  addMultilibFlag(ABIName == "lp64", "mabi=lp64", Flags);
1670
9
  addMultilibFlag(ABIName == "lp64f", "mabi=lp64f", Flags);
1671
9
  addMultilibFlag(ABIName == "lp64d", "mabi=lp64d", Flags);
1672
1673
9
  if (RISCVMultilibs.select(Flags, Result.SelectedMultilib))
1674
4
    Result.Multilibs = RISCVMultilibs;
1675
9
}
1676
1677
static bool findBiarchMultilibs(const Driver &D,
1678
                                const llvm::Triple &TargetTriple,
1679
                                StringRef Path, const ArgList &Args,
1680
                                bool NeedsBiarchSuffix,
1681
278
                                DetectedMultilibs &Result) {
1682
278
  Multilib Default;
1683
1684
  // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1685
  // in what would normally be GCCInstallPath and put the 64-bit
1686
  // libs in a subdirectory named 64. The simple logic we follow is that
1687
  // *if* there is a subdirectory of the right name with crtbegin.o in it,
1688
  // we use that. If not, and if not a biarch triple alias, we look for
1689
  // crtbegin.o without the subdirectory.
1690
1691
278
  StringRef Suff64 = "/64";
1692
  // Solaris uses platform-specific suffixes instead of /64.
1693
278
  if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1694
23
    switch (TargetTriple.getArch()) {
1695
4
    case llvm::Triple::x86:
1696
6
    case llvm::Triple::x86_64:
1697
6
      Suff64 = "/amd64";
1698
6
      break;
1699
15
    case llvm::Triple::sparc:
1700
17
    case llvm::Triple::sparcv9:
1701
17
      Suff64 = "/sparcv9";
1702
17
      break;
1703
0
    default:
1704
0
      break;
1705
278
    }
1706
278
  }
1707
1708
278
  Multilib Alt64 = Multilib()
1709
278
                       .gccSuffix(Suff64)
1710
278
                       .includeSuffix(Suff64)
1711
278
                       .flag("-m32")
1712
278
                       .flag("+m64")
1713
278
                       .flag("-mx32");
1714
278
  Multilib Alt32 = Multilib()
1715
278
                       .gccSuffix("/32")
1716
278
                       .includeSuffix("/32")
1717
278
                       .flag("+m32")
1718
278
                       .flag("-m64")
1719
278
                       .flag("-mx32");
1720
278
  Multilib Altx32 = Multilib()
1721
278
                        .gccSuffix("/x32")
1722
278
                        .includeSuffix("/x32")
1723
278
                        .flag("-m32")
1724
278
                        .flag("-m64")
1725
278
                        .flag("+mx32");
1726
1727
  // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a.
1728
278
  FilterNonExistent NonExistent(
1729
278
      Path, TargetTriple.isOSIAMCU() ? 
"/libgcc.a"0
: "/crtbegin.o", D.getVFS());
1730
1731
  // Determine default multilib from: 32, 64, x32
1732
  // Also handle cases such as 64 on 32, 32 on 64, etc.
1733
278
  enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
1734
278
  const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
1735
278
  if (TargetTriple.isArch32Bit() && 
!NonExistent(Alt32)131
)
1736
10
    Want = WANT64;
1737
268
  else if (TargetTriple.isArch64Bit() && 
IsX32147
&&
!NonExistent(Altx32)12
)
1738
8
    Want = WANT64;
1739
260
  else if (TargetTriple.isArch64Bit() && 
!IsX32139
&&
!NonExistent(Alt64)135
)
1740
7
    Want = WANT32;
1741
253
  else {
1742
253
    if (TargetTriple.isArch32Bit())
1743
121
      Want = NeedsBiarchSuffix ? 
WANT644
:
WANT32117
;
1744
132
    else if (IsX32)
1745
4
      Want = NeedsBiarchSuffix ? 
WANT640
: WANTX32;
1746
128
    else
1747
128
      Want = NeedsBiarchSuffix ? 
WANT321
:
WANT64127
;
1748
253
  }
1749
1750
278
  if (Want == WANT32)
1751
125
    Default.flag("+m32").flag("-m64").flag("-mx32");
1752
153
  else if (Want == WANT64)
1753
149
    Default.flag("-m32").flag("+m64").flag("-mx32");
1754
4
  else if (Want == WANTX32)
1755
4
    Default.flag("-m32").flag("-m64").flag("+mx32");
1756
0
  else
1757
0
    return false;
1758
1759
278
  Result.Multilibs.push_back(Default);
1760
278
  Result.Multilibs.push_back(Alt64);
1761
278
  Result.Multilibs.push_back(Alt32);
1762
278
  Result.Multilibs.push_back(Altx32);
1763
1764
278
  Result.Multilibs.FilterOut(NonExistent);
1765
1766
278
  Multilib::flags_list Flags;
1767
278
  addMultilibFlag(TargetTriple.isArch64Bit() && 
!IsX32147
, "m64", Flags);
1768
278
  addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
1769
278
  addMultilibFlag(TargetTriple.isArch64Bit() && 
IsX32147
, "mx32", Flags);
1770
1771
278
  if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
1772
9
    return false;
1773
1774
269
  if (Result.SelectedMultilib == Alt64 || 
Result.SelectedMultilib == Alt32262
||
1775
252
      Result.SelectedMultilib == Altx32)
1776
25
    Result.BiarchSibling = Default;
1777
1778
269
  return true;
1779
269
}
1780
1781
/// Generic_GCC - A tool chain using the 'gcc' command to perform
1782
/// all subcommands; this relies on gcc translating the majority of
1783
/// command line options.
1784
1785
/// Less-than for GCCVersion, implementing a Strict Weak Ordering.
1786
bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1787
                                          int RHSPatch,
1788
1.39k
                                          StringRef RHSPatchSuffix) const {
1789
1.39k
  if (Major != RHSMajor)
1790
580
    return Major < RHSMajor;
1791
812
  if (Minor != RHSMinor)
1792
656
    return Minor < RHSMinor;
1793
156
  if (Patch != RHSPatch) {
1794
    // Note that versions without a specified patch sort higher than those with
1795
    // a patch.
1796
7
    if (RHSPatch == -1)
1797
2
      return true;
1798
5
    if (Patch == -1)
1799
0
      return false;
1800
1801
    // Otherwise just sort on the patch itself.
1802
5
    return Patch < RHSPatch;
1803
5
  }
1804
149
  if (PatchSuffix != RHSPatchSuffix) {
1805
    // Sort empty suffixes higher.
1806
1
    if (RHSPatchSuffix.empty())
1807
1
      return true;
1808
0
    if (PatchSuffix.empty())
1809
0
      return false;
1810
1811
    // Provide a lexicographic sort to make this a total ordering.
1812
0
    return PatchSuffix < RHSPatchSuffix;
1813
0
  }
1814
1815
  // The versions are equal.
1816
148
  return false;
1817
148
}
1818
1819
/// Parse a GCCVersion object out of a string of text.
1820
///
1821
/// This is the primary means of forming GCCVersion objects.
1822
/*static*/
1823
6.60k
Generic_GCC::GCCVersion Generic_GCC::GCCVersion::Parse(StringRef VersionText) {
1824
6.60k
  const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1825
6.60k
  std::pair<StringRef, StringRef> First = VersionText.split('.');
1826
6.60k
  std::pair<StringRef, StringRef> Second = First.second.split('.');
1827
1828
6.60k
  GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1829
6.60k
  if (First.first.getAsInteger(10, GoodVersion.Major) || 
GoodVersion.Major < 06.59k
)
1830
1
    return BadVersion;
1831
6.59k
  GoodVersion.MajorStr = First.first.str();
1832
6.59k
  if (First.second.empty())
1833
20
    return GoodVersion;
1834
6.57k
  StringRef MinorStr = Second.first;
1835
6.57k
  if (Second.second.empty()) {
1836
152
    if (size_t EndNumber = MinorStr.find_first_not_of("0123456789")) {
1837
152
      GoodVersion.PatchSuffix = std::string(MinorStr.substr(EndNumber));
1838
152
      MinorStr = MinorStr.slice(0, EndNumber);
1839
152
    }
1840
152
  }
1841
6.57k
  if (MinorStr.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
1842
0
    return BadVersion;
1843
6.57k
  GoodVersion.MinorStr = MinorStr.str();
1844
1845
  // First look for a number prefix and parse that if present. Otherwise just
1846
  // stash the entire patch string in the suffix, and leave the number
1847
  // unspecified. This covers versions strings such as:
1848
  //   5        (handled above)
1849
  //   4.4
1850
  //   4.4-patched
1851
  //   4.4.0
1852
  //   4.4.x
1853
  //   4.4.2-rc4
1854
  //   4.4.x-patched
1855
  // And retains any patch number it finds.
1856
6.57k
  StringRef PatchText = Second.second;
1857
6.57k
  if (!PatchText.empty()) {
1858
6.42k
    if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1859
      // Try to parse the number and any suffix.
1860
6.42k
      if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1861
6.42k
          GoodVersion.Patch < 0)
1862
0
        return BadVersion;
1863
6.42k
      GoodVersion.PatchSuffix = std::string(PatchText.substr(EndNumber));
1864
6.42k
    }
1865
6.42k
  }
1866
1867
6.57k
  return GoodVersion;
1868
6.57k
}
1869
1870
static llvm::StringRef getGCCToolchainDir(const ArgList &Args,
1871
4.93k
                                          llvm::StringRef SysRoot) {
1872
4.93k
  const Arg *A = Args.getLastArg(clang::driver::options::OPT_gcc_toolchain);
1873
4.93k
  if (A)
1874
478
    return A->getValue();
1875
1876
  // If we have a SysRoot, ignore GCC_INSTALL_PREFIX.
1877
  // GCC_INSTALL_PREFIX specifies the gcc installation for the default
1878
  // sysroot and is likely not valid with a different sysroot.
1879
4.45k
  if (!SysRoot.empty())
1880
192
    return "";
1881
1882
4.26k
  return GCC_INSTALL_PREFIX;
1883
4.26k
}
1884
1885
/// Initialize a GCCInstallationDetector from the driver.
1886
///
1887
/// This performs all of the autodetection and sets up the various paths.
1888
/// Once constructed, a GCCInstallationDetector is essentially immutable.
1889
///
1890
/// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1891
/// should instead pull the target out of the driver. This is currently
1892
/// necessary because the driver doesn't store the final version of the target
1893
/// triple.
1894
void Generic_GCC::GCCInstallationDetector::init(
1895
    const llvm::Triple &TargetTriple, const ArgList &Args,
1896
4.93k
    ArrayRef<std::string> ExtraTripleAliases) {
1897
4.93k
  llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
1898
1.78k
                                         ? TargetTriple.get64BitArchVariant()
1899
3.15k
                                         : TargetTriple.get32BitArchVariant();
1900
  // The library directories which may contain GCC installations.
1901
4.93k
  SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1902
  // The compatible GCC triples for this particular architecture.
1903
4.93k
  SmallVector<StringRef, 16> CandidateTripleAliases;
1904
4.93k
  SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1905
4.93k
  CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1906
4.93k
                           CandidateTripleAliases, CandidateBiarchLibDirs,
1907
4.93k
                           CandidateBiarchTripleAliases);
1908
1909
  // Compute the set of prefixes for our search.
1910
4.93k
  SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1911
4.93k
                                       D.PrefixDirs.end());
1912
1913
4.93k
  StringRef GCCToolchainDir = getGCCToolchainDir(Args, D.SysRoot);
1914
4.93k
  if (GCCToolchainDir != "") {
1915
220
    if (GCCToolchainDir.back() == '/')
1916
1
      GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1917
1918
220
    Prefixes.push_back(std::string(GCCToolchainDir));
1919
4.71k
  } else {
1920
    // If we have a SysRoot, try that first.
1921
4.71k
    if (!D.SysRoot.empty()) {
1922
439
      Prefixes.push_back(D.SysRoot);
1923
439
      AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
1924
439
    }
1925
1926
    // Then look for gcc installed alongside clang.
1927
4.71k
    Prefixes.push_back(D.InstalledDir + "/..");
1928
1929
    // Next, look for prefix(es) that correspond to distribution-supplied gcc
1930
    // installations.
1931
4.71k
    if (D.SysRoot.empty()) {
1932
      // Typically /usr.
1933
4.27k
      AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
1934
4.27k
    }
1935
4.71k
  }
1936
1937
  // Try to respect gcc-config on Gentoo. However, do that only
1938
  // if --gcc-toolchain is not provided or equal to the Gentoo install
1939
  // in /usr. This avoids accidentally enforcing the system GCC version
1940
  // when using a custom toolchain.
1941
4.93k
  if (GCCToolchainDir == "" || 
GCCToolchainDir == D.SysRoot + "/usr"220
) {
1942
4.71k
    SmallVector<StringRef, 16> GentooTestTriples;
1943
    // Try to match an exact triple as target triple first.
1944
    // e.g. crossdev -S x86_64-gentoo-linux-gnu will install gcc libs for
1945
    // x86_64-gentoo-linux-gnu. But "clang -target x86_64-gentoo-linux-gnu"
1946
    // may pick the libraries for x86_64-pc-linux-gnu even when exact matching
1947
    // triple x86_64-gentoo-linux-gnu is present.
1948
4.71k
    GentooTestTriples.push_back(TargetTriple.str());
1949
    // Check rest of triples.
1950
4.71k
    GentooTestTriples.append(ExtraTripleAliases.begin(),
1951
4.71k
                             ExtraTripleAliases.end());
1952
4.71k
    GentooTestTriples.append(CandidateTripleAliases.begin(),
1953
4.71k
                             CandidateTripleAliases.end());
1954
4.71k
    if (ScanGentooConfigs(TargetTriple, Args, GentooTestTriples,
1955
4.71k
                          CandidateBiarchTripleAliases))
1956
9
      return;
1957
4.92k
  }
1958
1959
  // Loop over the various components which exist and select the best GCC
1960
  // installation available. GCC installs are ranked by version number.
1961
4.92k
  Version = GCCVersion::Parse("0.0.0");
1962
42.6k
  for (const std::string &Prefix : Prefixes) {
1963
42.6k
    auto &VFS = D.getVFS();
1964
42.6k
    if (!VFS.exists(Prefix))
1965
34.8k
      continue;
1966
12.8k
    
for (StringRef Suffix : CandidateLibDirs)7.81k
{
1967
12.8k
      const std::string LibDir = Prefix + Suffix.str();
1968
12.8k
      if (!VFS.exists(LibDir))
1969
5.48k
        continue;
1970
      // Maybe filter out <libdir>/gcc and <libdir>/gcc-cross.
1971
7.41k
      bool GCCDirExists = VFS.exists(LibDir + "/gcc");
1972
7.41k
      bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
1973
      // Try to match the exact target triple first.
1974
7.41k
      ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, TargetTriple.str(),
1975
7.41k
                             false, GCCDirExists, GCCCrossDirExists);
1976
      // Try rest of possible triples.
1977
7.41k
      for (StringRef Candidate : ExtraTripleAliases) // Try these first.
1978
46
        ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, false,
1979
46
                               GCCDirExists, GCCCrossDirExists);
1980
7.41k
      for (StringRef Candidate : CandidateTripleAliases)
1981
66.4k
        ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, false,
1982
66.4k
                               GCCDirExists, GCCCrossDirExists);
1983
7.41k
    }
1984
12.3k
    for (StringRef Suffix : CandidateBiarchLibDirs) {
1985
12.3k
      const std::string LibDir = Prefix + Suffix.str();
1986
12.3k
      if (!VFS.exists(LibDir))
1987
6.59k
        continue;
1988
5.79k
      bool GCCDirExists = VFS.exists(LibDir + "/gcc");
1989
5.79k
      bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
1990
5.79k
      for (StringRef Candidate : CandidateBiarchTripleAliases)
1991
70.6k
        ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, true,
1992
70.6k
                               GCCDirExists, GCCCrossDirExists);
1993
5.79k
    }
1994
7.81k
  }
1995
4.92k
}
1996
1997
105
void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1998
105
  for (const auto &InstallPath : CandidateGCCInstallPaths)
1999
12
    OS << "Found candidate GCC installation: " << InstallPath << "\n";
2000
2001
105
  if (!GCCInstallPath.empty())
2002
9
    OS << "Selected GCC installation: " << GCCInstallPath << "\n";
2003
2004
105
  for (const auto &Multilib : Multilibs)
2005
9
    OS << "Candidate multilib: " << Multilib << "\n";
2006
2007
105
  if (Multilibs.size() != 0 || 
!SelectedMultilib.isDefault()96
)
2008
9
    OS << "Selected multilib: " << SelectedMultilib << "\n";
2009
105
}
2010
2011
441
bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
2012
441
  if (BiarchSibling.hasValue()) {
2013
37
    M = BiarchSibling.getValue();
2014
37
    return true;
2015
37
  }
2016
404
  return false;
2017
404
}
2018
2019
void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
2020
    const llvm::Triple &TargetTriple, SmallVectorImpl<std::string> &Prefixes,
2021
4.71k
    StringRef SysRoot) {
2022
4.71k
  if (TargetTriple.getOS() == llvm::Triple::Solaris) {
2023
    // Solaris is a special case.
2024
    // The GCC installation is under
2025
    //   /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/
2026
    // so we need to find those /usr/gcc/*/lib/gcc libdirs and go with
2027
    // /usr/gcc/<version> as a prefix.
2028
2029
36
    std::string PrefixDir = SysRoot.str() + "/usr/gcc";
2030
36
    std::error_code EC;
2031
36
    for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, EC),
2032
36
                                       LE;
2033
59
         !EC && 
LI != LE46
;
LI = LI.increment(EC)23
) {
2034
23
      StringRef VersionText = llvm::sys::path::filename(LI->path());
2035
23
      GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2036
2037
      // Filter out obviously bad entries.
2038
23
      if (CandidateVersion.Major == -1 || CandidateVersion.isOlderThan(4, 1, 1))
2039
0
        continue;
2040
2041
23
      std::string CandidatePrefix = PrefixDir + "/" + VersionText.str();
2042
23
      std::string CandidateLibPath = CandidatePrefix + "/lib/gcc";
2043
23
      if (!D.getVFS().exists(CandidateLibPath))
2044
0
        continue;
2045
2046
23
      Prefixes.push_back(CandidatePrefix);
2047
23
    }
2048
36
    return;
2049
36
  }
2050
2051
  // Non-Solaris is much simpler - most systems just go with "/usr".
2052
4.67k
  if (SysRoot.empty() && 
TargetTriple.getOS() == llvm::Triple::Linux4.25k
) {
2053
    // Yet, still look for RHEL devtoolsets.
2054
4.07k
    Prefixes.push_back("/opt/rh/devtoolset-10/root/usr");
2055
4.07k
    Prefixes.push_back("/opt/rh/devtoolset-9/root/usr");
2056
4.07k
    Prefixes.push_back("/opt/rh/devtoolset-8/root/usr");
2057
4.07k
    Prefixes.push_back("/opt/rh/devtoolset-7/root/usr");
2058
4.07k
    Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
2059
4.07k
    Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
2060
4.07k
    Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
2061
4.07k
    Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
2062
4.07k
  }
2063
4.67k
  Prefixes.push_back(SysRoot.str() + "/usr");
2064
4.67k
}
2065
2066
/*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
2067
    const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
2068
    SmallVectorImpl<StringRef> &LibDirs,
2069
    SmallVectorImpl<StringRef> &TripleAliases,
2070
    SmallVectorImpl<StringRef> &BiarchLibDirs,
2071
4.93k
    SmallVectorImpl<StringRef> &BiarchTripleAliases) {
2072
  // Declare a bunch of static data sets that we'll select between below. These
2073
  // are specifically designed to always refer to string literals to avoid any
2074
  // lifetime or initialization issues.
2075
4.93k
  static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
2076
4.93k
  static const char *const AArch64Triples[] = {
2077
4.93k
      "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-redhat-linux",
2078
4.93k
      "aarch64-suse-linux", "aarch64-linux-android"};
2079
4.93k
  static const char *const AArch64beLibDirs[] = {"/lib"};
2080
4.93k
  static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
2081
4.93k
                                                 "aarch64_be-linux-gnu"};
2082
2083
4.93k
  static const char *const ARMLibDirs[] = {"/lib"};
2084
4.93k
  static const char *const ARMTriples[] = {"arm-linux-gnueabi",
2085
4.93k
                                           "arm-linux-androideabi"};
2086
4.93k
  static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
2087
4.93k
                                             "armv7hl-redhat-linux-gnueabi",
2088
4.93k
                                             "armv6hl-suse-linux-gnueabi",
2089
4.93k
                                             "armv7hl-suse-linux-gnueabi"};
2090
4.93k
  static const char *const ARMebLibDirs[] = {"/lib"};
2091
4.93k
  static const char *const ARMebTriples[] = {"armeb-linux-gnueabi",
2092
4.93k
                                             "armeb-linux-androideabi"};
2093
4.93k
  static const char *const ARMebHFTriples[] = {
2094
4.93k
      "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
2095
2096
4.93k
  static const char *const AVRLibDirs[] = {"/lib"};
2097
4.93k
  static const char *const AVRTriples[] = {"avr"};
2098
2099
4.93k
  static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
2100
4.93k
  static const char *const X86_64Triples[] = {
2101
4.93k
      "x86_64-linux-gnu",       "x86_64-unknown-linux-gnu",
2102
4.93k
      "x86_64-pc-linux-gnu",    "x86_64-redhat-linux6E",
2103
4.93k
      "x86_64-redhat-linux",    "x86_64-suse-linux",
2104
4.93k
      "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
2105
4.93k
      "x86_64-slackware-linux", "x86_64-unknown-linux",
2106
4.93k
      "x86_64-amazon-linux",    "x86_64-linux-android"};
2107
4.93k
  static const char *const X32LibDirs[] = {"/libx32"};
2108
4.93k
  static const char *const X86LibDirs[] = {"/lib32", "/lib"};
2109
4.93k
  static const char *const X86Triples[] = {
2110
4.93k
      "i686-linux-gnu",       "i686-pc-linux-gnu",     "i486-linux-gnu",
2111
4.93k
      "i386-linux-gnu",       "i386-redhat-linux6E",   "i686-redhat-linux",
2112
4.93k
      "i586-redhat-linux",    "i386-redhat-linux",     "i586-suse-linux",
2113
4.93k
      "i486-slackware-linux", "i686-montavista-linux", "i586-linux-gnu",
2114
4.93k
      "i686-linux-android",   "i386-gnu",              "i486-gnu",
2115
4.93k
      "i586-gnu",             "i686-gnu"};
2116
2117
4.93k
  static const char *const MIPSLibDirs[] = {"/lib"};
2118
4.93k
  static const char *const MIPSTriples[] = {
2119
4.93k
      "mips-linux-gnu", "mips-mti-linux", "mips-mti-linux-gnu",
2120
4.93k
      "mips-img-linux-gnu", "mipsisa32r6-linux-gnu"};
2121
4.93k
  static const char *const MIPSELLibDirs[] = {"/lib"};
2122
4.93k
  static const char *const MIPSELTriples[] = {
2123
4.93k
      "mipsel-linux-gnu", "mips-img-linux-gnu", "mipsisa32r6el-linux-gnu",
2124
4.93k
      "mipsel-linux-android"};
2125
2126
4.93k
  static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
2127
4.93k
  static const char *const MIPS64Triples[] = {
2128
4.93k
      "mips64-linux-gnu",      "mips-mti-linux-gnu",
2129
4.93k
      "mips-img-linux-gnu",    "mips64-linux-gnuabi64",
2130
4.93k
      "mipsisa64r6-linux-gnu", "mipsisa64r6-linux-gnuabi64"};
2131
4.93k
  static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
2132
4.93k
  static const char *const MIPS64ELTriples[] = {
2133
4.93k
      "mips64el-linux-gnu",      "mips-mti-linux-gnu",
2134
4.93k
      "mips-img-linux-gnu",      "mips64el-linux-gnuabi64",
2135
4.93k
      "mipsisa64r6el-linux-gnu", "mipsisa64r6el-linux-gnuabi64",
2136
4.93k
      "mips64el-linux-android"};
2137
2138
4.93k
  static const char *const MIPSN32LibDirs[] = {"/lib32"};
2139
4.93k
  static const char *const MIPSN32Triples[] = {"mips64-linux-gnuabin32",
2140
4.93k
                                               "mipsisa64r6-linux-gnuabin32"};
2141
4.93k
  static const char *const MIPSN32ELLibDirs[] = {"/lib32"};
2142
4.93k
  static const char *const MIPSN32ELTriples[] = {
2143
4.93k
      "mips64el-linux-gnuabin32", "mipsisa64r6el-linux-gnuabin32"};
2144
2145
4.93k
  static const char *const MSP430LibDirs[] = {"/lib"};
2146
4.93k
  static const char *const MSP430Triples[] = {"msp430-elf"};
2147
2148
4.93k
  static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
2149
4.93k
  static const char *const PPCTriples[] = {
2150
4.93k
      "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
2151
      // On 32-bit PowerPC systems running SUSE Linux, gcc is configured as a
2152
      // 64-bit compiler which defaults to "-m32", hence "powerpc64-suse-linux".
2153
4.93k
      "powerpc64-suse-linux", "powerpc-montavista-linuxspe"};
2154
4.93k
  static const char *const PPCLELibDirs[] = {"/lib32", "/lib"};
2155
4.93k
  static const char *const PPCLETriples[] = {"powerpcle-linux-gnu",
2156
4.93k
                                             "powerpcle-unknown-linux-gnu",
2157
4.93k
                                             "powerpcle-linux-musl"};
2158
2159
4.93k
  static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
2160
4.93k
  static const char *const PPC64Triples[] = {
2161
4.93k
      "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
2162
4.93k
      "powerpc64-suse-linux", "ppc64-redhat-linux"};
2163
4.93k
  static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
2164
4.93k
  static const char *const PPC64LETriples[] = {
2165
4.93k
      "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
2166
4.93k
      "powerpc64le-none-linux-gnu", "powerpc64le-suse-linux",
2167
4.93k
      "ppc64le-redhat-linux"};
2168
2169
4.93k
  static const char *const RISCV32LibDirs[] = {"/lib32", "/lib"};
2170
4.93k
  static const char *const RISCV32Triples[] = {"riscv32-unknown-linux-gnu",
2171
4.93k
                                               "riscv32-linux-gnu",
2172
4.93k
                                               "riscv32-unknown-elf"};
2173
4.93k
  static const char *const RISCV64LibDirs[] = {"/lib64", "/lib"};
2174
4.93k
  static const char *const RISCV64Triples[] = {"riscv64-unknown-linux-gnu",
2175
4.93k
                                               "riscv64-linux-gnu",
2176
4.93k
                                               "riscv64-unknown-elf",
2177
4.93k
                                               "riscv64-redhat-linux",
2178
4.93k
                                               "riscv64-suse-linux"};
2179
2180
4.93k
  static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
2181
4.93k
  static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
2182
4.93k
                                               "sparcv8-linux-gnu"};
2183
4.93k
  static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
2184
4.93k
  static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
2185
4.93k
                                               "sparcv9-linux-gnu"};
2186
2187
4.93k
  static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
2188
4.93k
  static const char *const SystemZTriples[] = {
2189
4.93k
      "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
2190
4.93k
      "s390x-suse-linux", "s390x-redhat-linux"};
2191
2192
2193
4.93k
  using std::begin;
2194
4.93k
  using std::end;
2195
2196
4.93k
  if (TargetTriple.getOS() == llvm::Triple::Solaris) {
2197
36
    static const char *const SolarisLibDirs[] = {"/lib"};
2198
36
    static const char *const SolarisSparcV8Triples[] = {
2199
36
        "sparc-sun-solaris2.11", "sparc-sun-solaris2.12"};
2200
36
    static const char *const SolarisSparcV9Triples[] = {
2201
36
        "sparcv9-sun-solaris2.11", "sparcv9-sun-solaris2.12"};
2202
36
    static const char *const SolarisX86Triples[] = {"i386-pc-solaris2.11",
2203
36
                                                    "i386-pc-solaris2.12"};
2204
36
    static const char *const SolarisX86_64Triples[] = {"x86_64-pc-solaris2.11",
2205
36
                                                       "x86_64-pc-solaris2.12"};
2206
36
    LibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2207
36
    BiarchLibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2208
36
    switch (TargetTriple.getArch()) {
2209
11
    case llvm::Triple::x86:
2210
11
      TripleAliases.append(begin(SolarisX86Triples), end(SolarisX86Triples));
2211
11
      BiarchTripleAliases.append(begin(SolarisX86_64Triples),
2212
11
                                 end(SolarisX86_64Triples));
2213
11
      break;
2214
3
    case llvm::Triple::x86_64:
2215
3
      TripleAliases.append(begin(SolarisX86_64Triples),
2216
3
                           end(SolarisX86_64Triples));
2217
3
      BiarchTripleAliases.append(begin(SolarisX86Triples),
2218
3
                                 end(SolarisX86Triples));
2219
3
      break;
2220
20
    case llvm::Triple::sparc:
2221
20
      TripleAliases.append(begin(SolarisSparcV8Triples),
2222
20
                           end(SolarisSparcV8Triples));
2223
20
      BiarchTripleAliases.append(begin(SolarisSparcV9Triples),
2224
20
                                 end(SolarisSparcV9Triples));
2225
20
      break;
2226
2
    case llvm::Triple::sparcv9:
2227
2
      TripleAliases.append(begin(SolarisSparcV9Triples),
2228
2
                           end(SolarisSparcV9Triples));
2229
2
      BiarchTripleAliases.append(begin(SolarisSparcV8Triples),
2230
2
                                 end(SolarisSparcV8Triples));
2231
2
      break;
2232
0
    default:
2233
0
      break;
2234
36
    }
2235
36
    return;
2236
36
  }
2237
2238
  // Android targets should not use GNU/Linux tools or libraries.
2239
4.89k
  if (TargetTriple.isAndroid()) {
2240
223
    static const char *const AArch64AndroidTriples[] = {
2241
223
        "aarch64-linux-android"};
2242
223
    static const char *const ARMAndroidTriples[] = {"arm-linux-androideabi"};
2243
223
    static const char *const MIPSELAndroidTriples[] = {"mipsel-linux-android"};
2244
223
    static const char *const MIPS64ELAndroidTriples[] = {
2245
223
        "mips64el-linux-android"};
2246
223
    static const char *const X86AndroidTriples[] = {"i686-linux-android"};
2247
223
    static const char *const X86_64AndroidTriples[] = {"x86_64-linux-android"};
2248
2249
223
    switch (TargetTriple.getArch()) {
2250
49
    case llvm::Triple::aarch64:
2251
49
      LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2252
49
      TripleAliases.append(begin(AArch64AndroidTriples),
2253
49
                           end(AArch64AndroidTriples));
2254
49
      break;
2255
99
    case llvm::Triple::arm:
2256
101
    case llvm::Triple::thumb:
2257
101
      LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2258
101
      TripleAliases.append(begin(ARMAndroidTriples), end(ARMAndroidTriples));
2259
101
      break;
2260
22
    case llvm::Triple::mipsel:
2261
22
      LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2262
22
      TripleAliases.append(begin(MIPSELAndroidTriples),
2263
22
                           end(MIPSELAndroidTriples));
2264
22
      BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2265
22
      BiarchTripleAliases.append(begin(MIPS64ELAndroidTriples),
2266
22
                                 end(MIPS64ELAndroidTriples));
2267
22
      break;
2268
10
    case llvm::Triple::mips64el:
2269
10
      LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2270
10
      TripleAliases.append(begin(MIPS64ELAndroidTriples),
2271
10
                           end(MIPS64ELAndroidTriples));
2272
10
      BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2273
10
      BiarchTripleAliases.append(begin(MIPSELAndroidTriples),
2274
10
                                 end(MIPSELAndroidTriples));
2275
10
      break;
2276
17
    case llvm::Triple::x86_64:
2277
17
      LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2278
17
      TripleAliases.append(begin(X86_64AndroidTriples),
2279
17
                           end(X86_64AndroidTriples));
2280
17
      BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2281
17
      BiarchTripleAliases.append(begin(X86AndroidTriples),
2282
17
                                 end(X86AndroidTriples));
2283
17
      break;
2284
24
    case llvm::Triple::x86:
2285
24
      LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2286
24
      TripleAliases.append(begin(X86AndroidTriples), end(X86AndroidTriples));
2287
24
      BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2288
24
      BiarchTripleAliases.append(begin(X86_64AndroidTriples),
2289
24
                                 end(X86_64AndroidTriples));
2290
24
      break;
2291
0
    default:
2292
0
      break;
2293
223
    }
2294
2295
223
    return;
2296
223
  }
2297
2298
4.67k
  switch (TargetTriple.getArch()) {
2299
211
  case llvm::Triple::aarch64:
2300
211
    LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2301
211
    TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2302
211
    BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2303
211
    BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2304
211
    break;
2305
8
  case llvm::Triple::aarch64_be:
2306
8
    LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2307
8
    TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2308
8
    BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2309
8
    BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2310
8
    break;
2311
447
  case llvm::Triple::arm:
2312
459
  case llvm::Triple::thumb:
2313
459
    LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2314
459
    if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2315
46
      TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
2316
413
    } else {
2317
413
      TripleAliases.append(begin(ARMTriples), end(ARMTriples));
2318
413
    }
2319
459
    break;
2320
43
  case llvm::Triple::armeb:
2321
54
  case llvm::Triple::thumbeb:
2322
54
    LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
2323
54
    if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2324
2
      TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
2325
52
    } else {
2326
52
      TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
2327
52
    }
2328
54
    break;
2329
28
  case llvm::Triple::avr:
2330
28
    LibDirs.append(begin(AVRLibDirs), end(AVRLibDirs));
2331
28
    TripleAliases.append(begin(AVRTriples), end(AVRTriples));
2332
28
    break;
2333
2.24k
  case llvm::Triple::x86_64:
2334
2.24k
    LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2335
2.24k
    TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2336
    // x32 is always available when x86_64 is available, so adding it as
2337
    // secondary arch with x86_64 triples
2338
2.24k
    if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
2339
11
      BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2340
11
      BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2341
2.23k
    } else {
2342
2.23k
      BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2343
2.23k
      BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
2344
2.23k
    }
2345
2.24k
    break;
2346
467
  case llvm::Triple::x86:
2347
467
    LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2348
    // MCU toolchain is 32 bit only and its triple alias is TargetTriple
2349
    // itself, which will be appended below.
2350
467
    if (!TargetTriple.isOSIAMCU()) {
2351
458
      TripleAliases.append(begin(X86Triples), end(X86Triples));
2352
458
      BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2353
458
      BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2354
458
    }
2355
467
    break;
2356
316
  case llvm::Triple::mips:
2357
316
    LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2358
316
    TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2359
316
    BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2360
316
    BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2361
316
    BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2362
316
    BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2363
316
    break;
2364
79
  case llvm::Triple::mipsel:
2365
79
    LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2366
79
    TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2367
79
    TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2368
79
    BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2369
79
    BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2370
79
    BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2371
79
    BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2372
79
    break;
2373
106
  case llvm::Triple::mips64:
2374
106
    LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2375
106
    TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2376
106
    BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2377
106
    BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2378
106
    BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2379
106
    BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2380
106
    break;
2381
66
  case llvm::Triple::mips64el:
2382
66
    LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2383
66
    TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2384
66
    BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2385
66
    BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2386
66
    BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2387
66
    BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2388
66
    BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2389
66
    break;
2390
51
  case llvm::Triple::msp430:
2391
51
    LibDirs.append(begin(MSP430LibDirs), end(MSP430LibDirs));
2392
51
    TripleAliases.append(begin(MSP430Triples), end(MSP430Triples));
2393
51
    break;
2394
32
  case llvm::Triple::ppc:
2395
32
    LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2396
32
    TripleAliases.append(begin(PPCTriples), end(PPCTriples));
2397
32
    BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2398
32
    BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2399
32
    break;
2400
3
  case llvm::Triple::ppcle:
2401
3
    LibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
2402
3
    TripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
2403
3
    BiarchLibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2404
3
    BiarchTripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2405
3
    break;
2406
106
  case llvm::Triple::ppc64:
2407
106
    LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2408
106
    TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2409
106
    BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2410
106
    BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
2411
106
    break;
2412
143
  case llvm::Triple::ppc64le:
2413
143
    LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2414
143
    TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2415
143
    BiarchLibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
2416
143
    BiarchTripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
2417
143
    break;
2418
49
  case llvm::Triple::riscv32:
2419
49
    LibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2420
49
    TripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2421
49
    BiarchLibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2422
49
    BiarchTripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2423
49
    break;
2424
45
  case llvm::Triple::riscv64:
2425
45
    LibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2426
45
    TripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2427
45
    BiarchLibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2428
45
    BiarchTripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2429
45
    break;
2430
23
  case llvm::Triple::sparc:
2431
43
  case llvm::Triple::sparcel:
2432
43
    LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2433
43
    TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2434
43
    BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2435
43
    BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2436
43
    break;
2437
16
  case llvm::Triple::sparcv9:
2438
16
    LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2439
16
    TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2440
16
    BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2441
16
    BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2442
16
    break;
2443
44
  case llvm::Triple::systemz:
2444
44
    LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
2445
44
    TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
2446
44
    break;
2447
103
  default:
2448
    // By default, just rely on the standard lib directories and the original
2449
    // triple.
2450
103
    break;
2451
4.67k
  }
2452
2453
  // Always append the drivers target triple to the end, in case it doesn't
2454
  // match any of our aliases.
2455
4.67k
  TripleAliases.push_back(TargetTriple.str());
2456
2457
  // Also include the multiarch variant if it's different.
2458
4.67k
  if (TargetTriple.str() != BiarchTriple.str())
2459
4.67k
    BiarchTripleAliases.push_back(BiarchTriple.str());
2460
4.67k
}
2461
2462
bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs(
2463
    const llvm::Triple &TargetTriple, const ArgList &Args,
2464
528
    StringRef Path, bool NeedsBiarchSuffix) {
2465
528
  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2466
528
  DetectedMultilibs Detected;
2467
2468
  // Android standalone toolchain could have multilibs for ARM and Thumb.
2469
  // Debian mips multilibs behave more like the rest of the biarch ones,
2470
  // so handle them there
2471
528
  if (isArmOrThumbArch(TargetArch) && 
TargetTriple.isAndroid()33
) {
2472
    // It should also work without multilibs in a simplified toolchain.
2473
18
    findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected);
2474
510
  } else if (TargetTriple.isMIPS()) {
2475
183
    if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected))
2476
0
      return false;
2477
327
  } else if (TargetTriple.isRISCV()) {
2478
36
    findRISCVMultilibs(D, TargetTriple, Path, Args, Detected);
2479
291
  } else if (isMSP430(TargetArch)) {
2480
13
    findMSP430Multilibs(D, TargetTriple, Path, Args, Detected);
2481
278
  } else if (TargetArch == llvm::Triple::avr) {
2482
    // AVR has no multilibs.
2483
278
  } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
2484
9
                                  NeedsBiarchSuffix, Detected)) {
2485
9
    return false;
2486
9
  }
2487
2488
519
  Multilibs = Detected.Multilibs;
2489
519
  SelectedMultilib = Detected.SelectedMultilib;
2490
519
  BiarchSibling = Detected.BiarchSibling;
2491
2492
519
  return true;
2493
519
}
2494
2495
void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2496
    const llvm::Triple &TargetTriple, const ArgList &Args,
2497
    const std::string &LibDir, StringRef CandidateTriple,
2498
144k
    bool NeedsBiarchSuffix, bool GCCDirExists, bool GCCCrossDirExists) {
2499
144k
  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2500
  // Locations relative to the system lib directory where GCC's triple-specific
2501
  // directories might reside.
2502
144k
  struct GCCLibSuffix {
2503
    // Path from system lib directory to GCC triple-specific directory.
2504
144k
    std::string LibSuffix;
2505
    // Path from GCC triple-specific directory back to system lib directory.
2506
    // This is one '..' component per component in LibSuffix.
2507
144k
    StringRef ReversePath;
2508
    // Whether this library suffix is relevant for the triple.
2509
144k
    bool Active;
2510
144k
  } Suffixes[] = {
2511
      // This is the normal place.
2512
144k
      {"gcc/" + CandidateTriple.str(), "../..", GCCDirExists},
2513
2514
      // Debian puts cross-compilers in gcc-cross.
2515
144k
      {"gcc-cross/" + CandidateTriple.str(), "../..", GCCCrossDirExists},
2516
2517
      // The Freescale PPC SDK has the gcc libraries in
2518
      // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well. Only do
2519
      // this on Freescale triples, though, since some systems put a *lot* of
2520
      // files in that location, not just GCC installation data.
2521
144k
      {CandidateTriple.str(), "..",
2522
144k
       TargetTriple.getVendor() == llvm::Triple::Freescale ||
2523
144k
       TargetTriple.getVendor() == llvm::Triple::OpenEmbedded},
2524
2525
      // Natively multiarch systems sometimes put the GCC triple-specific
2526
      // directory within their multiarch lib directory, resulting in the
2527
      // triple appearing twice.
2528
144k
      {CandidateTriple.str() + "/gcc/" + CandidateTriple.str(), "../../..",
2529
144k
       TargetTriple.getOS() != llvm::Triple::Solaris},
2530
2531
      // Deal with cases (on Ubuntu) where the system architecture could be i386
2532
      // but the GCC target architecture could be (say) i686.
2533
      // FIXME: It may be worthwhile to generalize this and look for a second
2534
      // triple.
2535
144k
      {"i386-linux-gnu/gcc/" + CandidateTriple.str(), "../../..",
2536
144k
       (TargetArch == llvm::Triple::x86 &&
2537
30.9k
        TargetTriple.getOS() != llvm::Triple::Solaris)},
2538
144k
      {"i386-gnu/gcc/" + CandidateTriple.str(), "../../..",
2539
144k
       (TargetArch == llvm::Triple::x86 &&
2540
30.9k
        TargetTriple.getOS() != llvm::Triple::Solaris)}};
2541
2542
867k
  for (auto &Suffix : Suffixes) {
2543
867k
    if (!Suffix.Active)
2544
651k
      continue;
2545
2546
216k
    StringRef LibSuffix = Suffix.LibSuffix;
2547
216k
    std::error_code EC;
2548
216k
    for (llvm::vfs::directory_iterator
2549
216k
             LI = D.getVFS().dir_begin(LibDir + "/" + LibSuffix, EC),
2550
216k
             LE;
2551
217k
         !EC && 
LI != LE2.54k
;
LI = LI.increment(EC)1.26k
) {
2552
1.26k
      StringRef VersionText = llvm::sys::path::filename(LI->path());
2553
1.26k
      GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2554
1.26k
      if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2555
1.26k
        if (!CandidateGCCInstallPaths.insert(std::string(LI->path())).second)
2556
582
          continue; // Saw this path before; no need to look at it again.
2557
678
      if (CandidateVersion.isOlderThan(4, 1, 1))
2558
0
        continue;
2559
678
      if (CandidateVersion <= Version)
2560
159
        continue;
2561
2562
519
      if (!ScanGCCForMultilibs(TargetTriple, Args, LI->path(),
2563
519
                               NeedsBiarchSuffix))
2564
9
        continue;
2565
2566
510
      Version = CandidateVersion;
2567
510
      GCCTriple.setTriple(CandidateTriple);
2568
      // FIXME: We hack together the directory name here instead of
2569
      // using LI to ensure stable path separators across Windows and
2570
      // Linux.
2571
510
      GCCInstallPath = (LibDir + "/" + LibSuffix + "/" + VersionText).str();
2572
510
      GCCParentLibPath = (GCCInstallPath + "/../" + Suffix.ReversePath).str();
2573
510
      IsValid = true;
2574
510
    }
2575
216k
  }
2576
144k
}
2577
2578
bool Generic_GCC::GCCInstallationDetector::ScanGentooConfigs(
2579
    const llvm::Triple &TargetTriple, const ArgList &Args,
2580
    const SmallVectorImpl<StringRef> &CandidateTriples,
2581
4.71k
    const SmallVectorImpl<StringRef> &CandidateBiarchTriples) {
2582
4.71k
  if (!D.getVFS().exists(D.SysRoot + GentooConfigDir))
2583
4.70k
    return false;
2584
2585
81
  
for (StringRef CandidateTriple : CandidateTriples)9
{
2586
81
    if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
2587
6
      return true;
2588
81
  }
2589
2590
9
  
for (StringRef CandidateTriple : CandidateBiarchTriples)3
{
2591
9
    if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple, true))
2592
3
      return true;
2593
9
  }
2594
0
  return false;
2595
3
}
2596
2597
bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
2598
    const llvm::Triple &TargetTriple, const ArgList &Args,
2599
90
    StringRef CandidateTriple, bool NeedsBiarchSuffix) {
2600
90
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2601
90
      D.getVFS().getBufferForFile(D.SysRoot + GentooConfigDir + "/config-" +
2602
90
                                  CandidateTriple.str());
2603
90
  if (File) {
2604
9
    SmallVector<StringRef, 2> Lines;
2605
9
    File.get()->getBuffer().split(Lines, "\n");
2606
9
    for (StringRef Line : Lines) {
2607
9
      Line = Line.trim();
2608
      // CURRENT=triple-version
2609
9
      if (!Line.consume_front("CURRENT="))
2610
0
        continue;
2611
      // Process the config file pointed to by CURRENT.
2612
9
      llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ConfigFile =
2613
9
          D.getVFS().getBufferForFile(D.SysRoot + GentooConfigDir + "/" +
2614
9
                                      Line.str());
2615
9
      std::pair<StringRef, StringRef> ActiveVersion = Line.rsplit('-');
2616
      // List of paths to scan for libraries.
2617
9
      SmallVector<StringRef, 4> GentooScanPaths;
2618
      // Scan the Config file to find installed GCC libraries path.
2619
      // Typical content of the GCC config file:
2620
      // LDPATH="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x:/usr/lib/gcc/
2621
      // (continued from previous line) x86_64-pc-linux-gnu/4.9.x/32"
2622
      // MANPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/man"
2623
      // INFOPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/info"
2624
      // STDCXX_INCDIR="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x/include/g++-v4"
2625
      // We are looking for the paths listed in LDPATH=... .
2626
9
      if (ConfigFile) {
2627
9
        SmallVector<StringRef, 2> ConfigLines;
2628
9
        ConfigFile.get()->getBuffer().split(ConfigLines, "\n");
2629
99
        for (StringRef ConfLine : ConfigLines) {
2630
99
          ConfLine = ConfLine.trim();
2631
99
          if (ConfLine.consume_front("LDPATH=")) {
2632
            // Drop '"' from front and back if present.
2633
9
            ConfLine.consume_back("\"");
2634
9
            ConfLine.consume_front("\"");
2635
            // Get all paths sperated by ':'
2636
9
            ConfLine.split(GentooScanPaths, ':', -1, /*AllowEmpty*/ false);
2637
9
          }
2638
99
        }
2639
9
      }
2640
      // Test the path based on the version in /etc/env.d/gcc/config-{tuple}.
2641
9
      std::string basePath = "/usr/lib/gcc/" + ActiveVersion.first.str() + "/"
2642
9
          + ActiveVersion.second.str();
2643
9
      GentooScanPaths.push_back(StringRef(basePath));
2644
2645
      // Scan all paths for GCC libraries.
2646
9
      for (const auto &GentooScanPath : GentooScanPaths) {
2647
9
        std::string GentooPath = D.SysRoot + std::string(GentooScanPath);
2648
9
        if (D.getVFS().exists(GentooPath + "/crtbegin.o")) {
2649
9
          if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath,
2650
9
                                   NeedsBiarchSuffix))
2651
0
            continue;
2652
2653
9
          Version = GCCVersion::Parse(ActiveVersion.second);
2654
9
          GCCInstallPath = GentooPath;
2655
9
          GCCParentLibPath = GentooPath + std::string("/../../..");
2656
9
          GCCTriple.setTriple(ActiveVersion.first);
2657
9
          IsValid = true;
2658
9
          return true;
2659
9
        }
2660
9
      }
2661
9
    }
2662
9
  }
2663
2664
81
  return false;
2665
90
}
2666
2667
Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
2668
                         const ArgList &Args)
2669
    : ToolChain(D, Triple, Args), GCCInstallation(D),
2670
16.9k
      CudaInstallation(D, Triple, Args), RocmInstallation(D, Triple, Args) {
2671
16.9k
  getProgramPaths().push_back(getDriver().getInstalledDir());
2672
16.9k
  if (getDriver().getInstalledDir() != getDriver().Dir)
2673
13
    getProgramPaths().push_back(getDriver().Dir);
2674
16.9k
}
2675
2676
16.9k
Generic_GCC::~Generic_GCC() {}
2677
2678
3.33k
Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
2679
3.33k
  switch (AC) {
2680
0
  case Action::PreprocessJobClass:
2681
0
    if (!Preprocess)
2682
0
      Preprocess.reset(new clang::driver::tools::gcc::Preprocessor(*this));
2683
0
    return Preprocess.get();
2684
4
  case Action::CompileJobClass:
2685
4
    if (!Compile)
2686
4
      Compile.reset(new tools::gcc::Compiler(*this));
2687
4
    return Compile.get();
2688
3.32k
  default:
2689
3.32k
    return ToolChain::getTool(AC);
2690
3.33k
  }
2691
3.33k
}
2692
2693
143
Tool *Generic_GCC::buildAssembler() const {
2694
143
  return new tools::gnutools::Assembler(*this);
2695
143
}
2696
2697
284
Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2698
2699
105
void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2700
  // Print the information about how we detected the GCC installation.
2701
105
  GCCInstallation.print(OS);
2702
105
  CudaInstallation.print(OS);
2703
105
  RocmInstallation.print(OS);
2704
105
}
2705
2706
16.3k
bool Generic_GCC::IsUnwindTablesDefault(const ArgList &Args) const {
2707
16.3k
  switch (getArch()) {
2708
867
  case llvm::Triple::aarch64:
2709
912
  case llvm::Triple::ppc:
2710
918
  case llvm::Triple::ppcle:
2711
1.03k
  case llvm::Triple::ppc64:
2712
1.20k
  case llvm::Triple::ppc64le:
2713
3.74k
  case llvm::Triple::x86_64:
2714
3.74k
    return true;
2715
12.5k
  default:
2716
12.5k
    return false;
2717
16.3k
  }
2718
16.3k
}
2719
2720
17.2k
bool Generic_GCC::isPICDefault() const {
2721
17.2k
  switch (getArch()) {
2722
2.53k
  case llvm::Triple::x86_64:
2723
2.53k
    return getTriple().isOSWindows();
2724
288
  case llvm::Triple::mips64:
2725
442
  case llvm::Triple::mips64el:
2726
442
    return true;
2727
14.3k
  default:
2728
14.3k
    return false;
2729
17.2k
  }
2730
17.2k
}
2731
2732
11.9k
bool Generic_GCC::isPIEDefault() const { return false; }
2733
2734
17.7k
bool Generic_GCC::isPICDefaultForced() const {
2735
17.7k
  return getArch() == llvm::Triple::x86_64 && 
getTriple().isOSWindows()2.75k
;
2736
17.7k
}
2737
2738
98.7k
bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2739
98.7k
  switch (getTriple().getArch()) {
2740
58.1k
  case llvm::Triple::x86:
2741
74.5k
  case llvm::Triple::x86_64:
2742
79.4k
  case llvm::Triple::aarch64:
2743
80.4k
  case llvm::Triple::aarch64_be:
2744
86.2k
  case llvm::Triple::arm:
2745
86.9k
  case llvm::Triple::armeb:
2746
87.5k
  case llvm::Triple::avr:
2747
87.6k
  case llvm::Triple::bpfel:
2748
87.7k
  case llvm::Triple::bpfeb:
2749
87.8k
  case llvm::Triple::thumb:
2750
87.9k
  case llvm::Triple::thumbeb:
2751
88.3k
  case llvm::Triple::ppc:
2752
88.3k
  case llvm::Triple::ppcle:
2753
89.2k
  case llvm::Triple::ppc64:
2754
90.3k
  case llvm::Triple::ppc64le:
2755
90.5k
  case llvm::Triple::riscv32:
2756
90.7k
  case llvm::Triple::riscv64:
2757
91.1k
  case llvm::Triple::systemz:
2758
92.9k
  case llvm::Triple::mips:
2759
93.6k
  case llvm::Triple::mipsel:
2760
94.5k
  case llvm::Triple::mips64:
2761
95.1k
  case llvm::Triple::mips64el:
2762
95.5k
  case llvm::Triple::msp430:
2763
95.5k
    return true;
2764
929
  case llvm::Triple::sparc:
2765
1.06k
  case llvm::Triple::sparcel:
2766
1.55k
  case llvm::Triple::sparcv9:
2767
1.55k
    if (getTriple().isOSFreeBSD() || 
getTriple().isOSOpenBSD()1.52k
||
2768
1.50k
        getTriple().isOSSolaris())
2769
194
      return true;
2770
1.35k
    return false;
2771
1.67k
  default:
2772
1.67k
    return false;
2773
98.7k
  }
2774
98.7k
}
2775
2776
static void addMultilibsFilePaths(const Driver &D, const MultilibSet &Multilibs,
2777
                                  const Multilib &Multilib,
2778
                                  StringRef InstallPath,
2779
441
                                  ToolChain::path_list &Paths) {
2780
441
  if (const auto &PathsCallback = Multilibs.filePathsCallback())
2781
28
    for (const auto &Path : PathsCallback(Multilib))
2782
28
      addPathIfExists(D, InstallPath + Path, Paths);
2783
441
}
2784
2785
4.76k
void Generic_GCC::PushPPaths(ToolChain::path_list &PPaths) {
2786
  // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
2787
  // least) put various tools in a triple-prefixed directory off of the parent
2788
  // of the GCC installation. We use the GCC triple here to ensure that we end
2789
  // up with tools that support the same amount of cross compiling as the
2790
  // detected GCC installation. For example, if we find a GCC installation
2791
  // targeting x86_64, but it is a bi-arch GCC installation, it can also be
2792
  // used to target i386.
2793
4.76k
  if (GCCInstallation.isValid()) {
2794
441
    PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2795
441
                           GCCInstallation.getTriple().str() + "/bin")
2796
441
                         .str());
2797
441
  }
2798
4.76k
}
2799
2800
void Generic_GCC::AddMultilibPaths(const Driver &D,
2801
                                   const std::string &SysRoot,
2802
                                   const std::string &OSLibDir,
2803
                                   const std::string &MultiarchTriple,
2804
4.76k
                                   path_list &Paths) {
2805
  // Add the multilib suffixed paths where they are available.
2806
4.76k
  if (GCCInstallation.isValid()) {
2807
441
    const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2808
441
    const std::string &LibPath =
2809
441
        std::string(GCCInstallation.getParentLibPath());
2810
2811
    // Add toolchain / multilib specific file paths.
2812
441
    addMultilibsFilePaths(D, Multilibs, SelectedMultilib,
2813
441
                          GCCInstallation.getInstallPath(), Paths);
2814
2815
    // Sourcery CodeBench MIPS toolchain holds some libraries under
2816
    // a biarch-like suffix of the GCC installation.
2817
441
    addPathIfExists(
2818
441
        D, GCCInstallation.getInstallPath() + SelectedMultilib.gccSuffix(),
2819
441
        Paths);
2820
2821
    // GCC cross compiling toolchains will install target libraries which ship
2822
    // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
2823
    // any part of the GCC installation in
2824
    // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
2825
    // debatable, but is the reality today. We need to search this tree even
2826
    // when we have a sysroot somewhere else. It is the responsibility of
2827
    // whomever is doing the cross build targeting a sysroot using a GCC
2828
    // installation that is *not* within the system root to ensure two things:
2829
    //
2830
    //  1) Any DSOs that are linked in from this tree or from the install path
2831
    //     above must be present on the system root and found via an
2832
    //     appropriate rpath.
2833
    //  2) There must not be libraries installed into
2834
    //     <prefix>/<triple>/<libdir> unless they should be preferred over
2835
    //     those within the system root.
2836
    //
2837
    // Note that this matches the GCC behavior. See the below comment for where
2838
    // Clang diverges from GCC's behavior.
2839
441
    addPathIfExists(D,
2840
441
                    LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
2841
441
                        SelectedMultilib.osSuffix(),
2842
441
                    Paths);
2843
2844
    // If the GCC installation we found is inside of the sysroot, we want to
2845
    // prefer libraries installed in the parent prefix of the GCC installation.
2846
    // It is important to *not* use these paths when the GCC installation is
2847
    // outside of the system root as that can pick up unintended libraries.
2848
    // This usually happens when there is an external cross compiler on the
2849
    // host system, and a more minimal sysroot available that is the target of
2850
    // the cross. Note that GCC does include some of these directories in some
2851
    // configurations but this seems somewhere between questionable and simply
2852
    // a bug.
2853
441
    if (StringRef(LibPath).startswith(SysRoot)) {
2854
241
      addPathIfExists(D, LibPath + "/" + MultiarchTriple, Paths);
2855
241
      addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
2856
241
    }
2857
441
  }
2858
4.76k
}
2859
2860
void Generic_GCC::AddMultiarchPaths(const Driver &D,
2861
                                    const std::string &SysRoot,
2862
                                    const std::string &OSLibDir,
2863
4.76k
                                    path_list &Paths) {
2864
  // Try walking via the GCC triple path in case of biarch or multiarch GCC
2865
  // installations with strange symlinks.
2866
4.76k
  if (GCCInstallation.isValid()) {
2867
441
    addPathIfExists(D,
2868
441
                    SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
2869
441
                        "/../../" + OSLibDir,
2870
441
                    Paths);
2871
2872
    // Add the 'other' biarch variant path
2873
441
    Multilib BiarchSibling;
2874
441
    if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
2875
37
      addPathIfExists(
2876
37
          D, GCCInstallation.getInstallPath() + BiarchSibling.gccSuffix(),
2877
37
                      Paths);
2878
37
    }
2879
2880
    // See comments above on the multilib variant for details of why this is
2881
    // included even from outside the sysroot.
2882
441
    const std::string &LibPath =
2883
441
        std::string(GCCInstallation.getParentLibPath());
2884
441
    const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2885
441
    const Multilib &Multilib = GCCInstallation.getMultilib();
2886
441
    addPathIfExists(
2887
441
        D, LibPath + "/../" + GCCTriple.str() + "/lib" + Multilib.osSuffix(),
2888
441
                    Paths);
2889
2890
    // See comments above on the multilib variant for details of why this is
2891
    // only included from within the sysroot.
2892
441
    if (StringRef(LibPath).startswith(SysRoot))
2893
241
      addPathIfExists(D, LibPath, Paths);
2894
441
  }
2895
4.76k
}
2896
2897
void Generic_GCC::AddMultilibIncludeArgs(const ArgList &DriverArgs,
2898
5.36k
                                         ArgStringList &CC1Args) const {
2899
  // Add include directories specific to the selected multilib set and multilib.
2900
5.36k
  if (GCCInstallation.isValid()) {
2901
448
    const auto &Callback = Multilibs.includeDirsCallback();
2902
448
    if (Callback) {
2903
163
      for (const auto &Path : Callback(GCCInstallation.getMultilib()))
2904
298
        addExternCSystemIncludeIfExists(
2905
298
            DriverArgs, CC1Args, GCCInstallation.getInstallPath() + Path);
2906
163
    }
2907
448
  }
2908
5.36k
}
2909
2910
void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2911
10.5k
                                               ArgStringList &CC1Args) const {
2912
10.5k
  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2913
10.5k
      DriverArgs.hasArg(options::OPT_nostdincxx))
2914
19
    return;
2915
2916
10.4k
  switch (GetCXXStdlibType(DriverArgs)) {
2917
95
  case ToolChain::CST_Libcxx:
2918
95
    addLibCxxIncludePaths(DriverArgs, CC1Args);
2919
95
    break;
2920
2921
10.4k
  case ToolChain::CST_Libstdcxx:
2922
10.4k
    addLibStdCxxIncludePaths(DriverArgs, CC1Args);
2923
10.4k
    break;
2924
10.4k
  }
2925
10.4k
}
2926
2927
static std::string DetectLibcxxIncludePath(llvm::vfs::FileSystem &vfs,
2928
67
                                           StringRef base) {
2929
67
  std::error_code EC;
2930
67
  int MaxVersion = 0;
2931
67
  std::string MaxVersionString;
2932
67
  for (llvm::vfs::directory_iterator LI = vfs.dir_begin(base, EC), LE;
2933
96
       !EC && 
LI != LE54
;
LI = LI.increment(EC)29
) {
2934
29
    StringRef VersionText = llvm::sys::path::filename(LI->path());
2935
29
    int Version;
2936
29
    if (VersionText[0] == 'v' &&
2937
28
        !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
2938
28
      if (Version > MaxVersion) {
2939
28
        MaxVersion = Version;
2940
28
        MaxVersionString = std::string(VersionText);
2941
28
      }
2942
28
    }
2943
29
  }
2944
42
  return MaxVersion ? 
(base + "/" + MaxVersionString).str()25
: "";
2945
67
}
2946
2947
void
2948
Generic_GCC::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
2949
34
                                   llvm::opt::ArgStringList &CC1Args) const {
2950
67
  auto AddIncludePath = [&](std::string Path) {
2951
67
    std::string IncludePath = DetectLibcxxIncludePath(getVFS(), Path);
2952
67
    if (IncludePath.empty() || 
!getVFS().exists(IncludePath)25
)
2953
42
      return false;
2954
25
    addSystemInclude(DriverArgs, CC1Args, IncludePath);
2955
25
    return true;
2956
25
  };
2957
  // Android never uses the libc++ headers installed alongside the toolchain,
2958
  // which are generally incompatible with the NDK libraries anyway.
2959
34
  if (!getTriple().isAndroid())
2960
11
    if (AddIncludePath(getDriver().Dir + "/../include/c++"))
2961
6
      return;
2962
  // If this is a development, non-installed, clang, libcxx will
2963
  // not be found at ../include/c++ but it likely to be found at
2964
  // one of the following two locations:
2965
28
  std::string SysRoot = computeSysRoot();
2966
28
  if (AddIncludePath(SysRoot + "/usr/local/include/c++"))
2967
0
    return;
2968
28
  if (AddIncludePath(SysRoot + "/usr/include/c++"))
2969
19
    return;
2970
28
}
2971
2972
/// Helper to add the variant paths of a libstdc++ installation.
2973
bool Generic_GCC::addLibStdCXXIncludePaths(
2974
    Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple,
2975
    StringRef TargetMultiarchTriple, Twine IncludeSuffix,
2976
1.21k
    const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2977
1.21k
  if (!getVFS().exists(Base + Suffix))
2978
982
    return false;
2979
2980
228
  addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
2981
2982
  // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
2983
  // that path exists or we have neither a GCC nor target multiarch triple, use
2984
  // this vanilla search path.
2985
228
  if ((GCCMultiarchTriple.empty() && 
TargetMultiarchTriple.empty()200
) ||
2986
214
      
getVFS().exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)28
) {
2987
214
    addSystemInclude(DriverArgs, CC1Args,
2988
214
                     Base + Suffix + "/" + GCCTriple + IncludeSuffix);
2989
14
  } else {
2990
    // Otherwise try to use multiarch naming schemes which have normalized the
2991
    // triples and put the triple before the suffix.
2992
    //
2993
    // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
2994
    // the target triple, so we support that here.
2995
14
    addSystemInclude(DriverArgs, CC1Args,
2996
14
                     Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
2997
14
    addSystemInclude(DriverArgs, CC1Args,
2998
14
                     Base + "/" + TargetMultiarchTriple + Suffix);
2999
14
  }
3000
3001
228
  addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
3002
228
  return true;
3003
228
}
3004
3005
bool
3006
Generic_GCC::addGCCLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3007
10.2k
                                         llvm::opt::ArgStringList &CC1Args) const {
3008
  // Use GCCInstallation to know where libstdc++ headers are installed.
3009
10.2k
  if (!GCCInstallation.isValid())
3010
10.0k
    return false;
3011
3012
  // By default, look for the C++ headers in an include directory adjacent to
3013
  // the lib directory of the GCC installation. Note that this is expect to be
3014
  // equivalent to '/usr/include/c++/X.Y' in almost all cases.
3015
232
  StringRef LibDir = GCCInstallation.getParentLibPath();
3016
232
  StringRef InstallDir = GCCInstallation.getInstallPath();
3017
232
  StringRef TripleStr = GCCInstallation.getTriple().str();
3018
232
  const Multilib &Multilib = GCCInstallation.getMultilib();
3019
232
  const std::string GCCMultiarchTriple = getMultiarchTriple(
3020
232
      getDriver(), GCCInstallation.getTriple(), getDriver().SysRoot);
3021
232
  const std::string TargetMultiarchTriple =
3022
232
      getMultiarchTriple(getDriver(), getTriple(), getDriver().SysRoot);
3023
232
  const GCCVersion &Version = GCCInstallation.getVersion();
3024
3025
  // The primary search for libstdc++ supports multiarch variants.
3026
232
  if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
3027
232
                               "/c++/" + Version.Text, TripleStr,
3028
232
                               GCCMultiarchTriple, TargetMultiarchTriple,
3029
232
                               Multilib.includeSuffix(), DriverArgs, CC1Args))
3030
28
    return true;
3031
3032
  // Otherwise, fall back on a bunch of options which don't use multiarch
3033
  // layouts for simplicity.
3034
204
  const std::string LibStdCXXIncludePathCandidates[] = {
3035
      // Gentoo is weird and places its headers inside the GCC install,
3036
      // so if the first attempt to find the headers fails, try these patterns.
3037
204
      InstallDir.str() + "/include/g++-v" + Version.Text,
3038
204
      InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
3039
204
          Version.MinorStr,
3040
204
      InstallDir.str() + "/include/g++-v" + Version.MajorStr,
3041
204
  };
3042
3043
597
  for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
3044
597
    if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
3045
597
                                 /*GCCMultiarchTriple*/ "",
3046
597
                                 /*TargetMultiarchTriple*/ "",
3047
597
                                 Multilib.includeSuffix(), DriverArgs, CC1Args))
3048
9
      return true;
3049
597
  }
3050
195
  return false;
3051
204
}
3052
3053
void
3054
Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3055
7.65k
                                      llvm::opt::ArgStringList &CC1Args) const {
3056
7.65k
  addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args);
3057
7.65k
}
3058
3059
llvm::opt::DerivedArgList *
3060
Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef,
3061
17.6k
                           Action::OffloadKind DeviceOffloadKind) const {
3062
3063
  // If this tool chain is used for an OpenMP offloading device we have to make
3064
  // sure we always generate a shared library regardless of the commands the
3065
  // user passed to the host. This is required because the runtime library
3066
  // is required to load the device image dynamically at run time.
3067
17.6k
  if (DeviceOffloadKind == Action::OFK_OpenMP) {
3068
44
    DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3069
44
    const OptTable &Opts = getDriver().getOpts();
3070
3071
    // Request the shared library. Given that these options are decided
3072
    // implicitly, they do not refer to any base argument.
3073
44
    DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared));
3074
44
    DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC));
3075
3076
    // Filter all the arguments we don't care passing to the offloading
3077
    // toolchain as they can mess up with the creation of a shared library.
3078
385
    for (auto *A : Args) {
3079
385
      switch ((options::ID)A->getOption().getID()) {
3080
385
      default:
3081
385
        DAL->append(A);
3082
385
        break;
3083
0
      case options::OPT_shared:
3084
0
      case options::OPT_dynamic:
3085
0
      case options::OPT_static:
3086
0
      case options::OPT_fPIC:
3087
0
      case options::OPT_fno_PIC:
3088
0
      case options::OPT_fpic:
3089
0
      case options::OPT_fno_pic:
3090
0
      case options::OPT_fPIE:
3091
0
      case options::OPT_fno_PIE:
3092
0
      case options::OPT_fpie:
3093
0
      case options::OPT_fno_pie:
3094
0
        break;
3095
385
      }
3096
385
    }
3097
44
    return DAL;
3098
17.6k
  }
3099
17.6k
  return nullptr;
3100
17.6k
}
3101
3102
0
void Generic_ELF::anchor() {}
3103
3104
void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
3105
                                        ArgStringList &CC1Args,
3106
16.0k
                                        Action::OffloadKind) const {
3107
16.0k
  if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
3108
16.0k
                          options::OPT_fno_use_init_array, true))
3109
1
    CC1Args.push_back("-fno-use-init-array");
3110
16.0k
}