Coverage Report

Created: 2020-02-25 14:32

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