Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Driver/ToolChains/CommonArgs.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CommonArgs.cpp - Args handling for multiple toolchains -*- 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 "CommonArgs.h"
10
#include "Arch/AArch64.h"
11
#include "Arch/ARM.h"
12
#include "Arch/M68k.h"
13
#include "Arch/Mips.h"
14
#include "Arch/PPC.h"
15
#include "Arch/SystemZ.h"
16
#include "Arch/VE.h"
17
#include "Arch/X86.h"
18
#include "HIP.h"
19
#include "Hexagon.h"
20
#include "clang/Basic/CharInfo.h"
21
#include "clang/Basic/LangOptions.h"
22
#include "clang/Basic/ObjCRuntime.h"
23
#include "clang/Basic/Version.h"
24
#include "clang/Config/config.h"
25
#include "clang/Driver/Action.h"
26
#include "clang/Driver/Compilation.h"
27
#include "clang/Driver/Driver.h"
28
#include "clang/Driver/DriverDiagnostic.h"
29
#include "clang/Driver/InputInfo.h"
30
#include "clang/Driver/Job.h"
31
#include "clang/Driver/Options.h"
32
#include "clang/Driver/SanitizerArgs.h"
33
#include "clang/Driver/ToolChain.h"
34
#include "clang/Driver/Util.h"
35
#include "clang/Driver/XRayArgs.h"
36
#include "llvm/ADT/STLExtras.h"
37
#include "llvm/ADT/SmallString.h"
38
#include "llvm/ADT/StringExtras.h"
39
#include "llvm/ADT/StringSwitch.h"
40
#include "llvm/ADT/Twine.h"
41
#include "llvm/Config/llvm-config.h"
42
#include "llvm/Option/Arg.h"
43
#include "llvm/Option/ArgList.h"
44
#include "llvm/Option/Option.h"
45
#include "llvm/Support/CodeGen.h"
46
#include "llvm/Support/Compression.h"
47
#include "llvm/Support/Debug.h"
48
#include "llvm/Support/ErrorHandling.h"
49
#include "llvm/Support/FileSystem.h"
50
#include "llvm/Support/Host.h"
51
#include "llvm/Support/Path.h"
52
#include "llvm/Support/Process.h"
53
#include "llvm/Support/Program.h"
54
#include "llvm/Support/ScopedPrinter.h"
55
#include "llvm/Support/TargetParser.h"
56
#include "llvm/Support/Threading.h"
57
#include "llvm/Support/VirtualFileSystem.h"
58
#include "llvm/Support/YAMLParser.h"
59
60
using namespace clang::driver;
61
using namespace clang::driver::tools;
62
using namespace clang;
63
using namespace llvm::opt;
64
65
300
static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs) {
66
300
  if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
67
2
    CmdArgs.push_back(Args.MakeArgString(Twine("--plugin-opt=-pass-remarks=") +
68
2
                                         A->getValue()));
69
70
300
  if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
71
2
    CmdArgs.push_back(Args.MakeArgString(
72
2
        Twine("--plugin-opt=-pass-remarks-missed=") + A->getValue()));
73
74
300
  if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
75
2
    CmdArgs.push_back(Args.MakeArgString(
76
2
        Twine("--plugin-opt=-pass-remarks-analysis=") + A->getValue()));
77
300
}
78
79
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
80
                                 const llvm::Triple &Triple,
81
                                 const InputInfo &Input,
82
3
                                 const InputInfo &Output) {
83
3
  StringRef Format = "yaml";
84
3
  if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
85
1
    Format = A->getValue();
86
87
3
  SmallString<128> F;
88
3
  const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
89
3
  if (A)
90
1
    F = A->getValue();
91
2
  else if (Output.isFilename())
92
2
    F = Output.getFilename();
93
94
3
  assert(!F.empty() && "Cannot determine remarks output name.");
95
  // Append "opt.ld.<format>" to the end of the file name.
96
0
  CmdArgs.push_back(
97
3
      Args.MakeArgString(Twine("--plugin-opt=opt-remarks-filename=") + F +
98
3
                         Twine(".opt.ld.") + Format));
99
100
3
  if (const Arg *A =
101
3
          Args.getLastArg(options::OPT_foptimization_record_passes_EQ))
102
2
    CmdArgs.push_back(Args.MakeArgString(
103
2
        Twine("--plugin-opt=opt-remarks-passes=") + A->getValue()));
104
105
3
  CmdArgs.push_back(Args.MakeArgString(
106
3
      Twine("--plugin-opt=opt-remarks-format=") + Format.data()));
107
3
}
108
109
static void renderRemarksHotnessOptions(const ArgList &Args,
110
300
                                        ArgStringList &CmdArgs) {
111
300
  if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
112
300
                   options::OPT_fno_diagnostics_show_hotness, false))
113
0
    CmdArgs.push_back("--plugin-opt=opt-remarks-with-hotness");
114
115
300
  if (const Arg *A =
116
300
          Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ))
117
5
    CmdArgs.push_back(Args.MakeArgString(
118
5
        Twine("--plugin-opt=opt-remarks-hotness-threshold=") + A->getValue()));
119
300
}
120
121
void tools::addPathIfExists(const Driver &D, const Twine &Path,
122
41.9k
                            ToolChain::path_list &Paths) {
123
41.9k
  if (D.getVFS().exists(Path))
124
10.4k
    Paths.push_back(Path.str());
125
41.9k
}
126
127
void tools::handleTargetFeaturesGroup(const ArgList &Args,
128
                                      std::vector<StringRef> &Features,
129
1.95k
                                      OptSpecifier Group) {
130
1.95k
  for (const Arg *A : Args.filtered(Group)) {
131
192
    StringRef Name = A->getOption().getName();
132
192
    A->claim();
133
134
    // Skip over "-m".
135
192
    assert(Name.startswith("m") && "Invalid feature name.");
136
0
    Name = Name.substr(1);
137
138
192
    bool IsNegative = Name.startswith("no-");
139
192
    if (IsNegative)
140
69
      Name = Name.substr(3);
141
192
    Features.push_back(Args.MakeArgString((IsNegative ? 
"-"69
:
"+"123
) + Name));
142
192
  }
143
1.95k
}
144
145
std::vector<StringRef>
146
44.5k
tools::unifyTargetFeatures(const std::vector<StringRef> &Features) {
147
44.5k
  std::vector<StringRef> UnifiedFeatures;
148
  // Find the last of each feature.
149
44.5k
  llvm::StringMap<unsigned> LastOpt;
150
135k
  for (unsigned I = 0, N = Features.size(); I < N; 
++I90.5k
) {
151
90.5k
    StringRef Name = Features[I];
152
90.5k
    assert(Name[0] == '-' || Name[0] == '+');
153
0
    LastOpt[Name.drop_front(1)] = I;
154
90.5k
  }
155
156
135k
  for (unsigned I = 0, N = Features.size(); I < N; 
++I90.5k
) {
157
    // If this feature was overridden, ignore it.
158
90.5k
    StringRef Name = Features[I];
159
90.5k
    llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
160
90.5k
    assert(LastI != LastOpt.end());
161
0
    unsigned Last = LastI->second;
162
90.5k
    if (Last != I)
163
22.6k
      continue;
164
165
67.9k
    UnifiedFeatures.push_back(Name);
166
67.9k
  }
167
44.5k
  return UnifiedFeatures;
168
44.5k
}
169
170
void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
171
219k
                             const char *ArgName, const char *EnvVar) {
172
219k
  const char *DirList = ::getenv(EnvVar);
173
219k
  bool CombinedArg = false;
174
175
219k
  if (!DirList)
176
219k
    return; // Nothing to do.
177
178
71
  StringRef Name(ArgName);
179
71
  if (Name.equals("-I") || 
Name.equals("-L")44
||
Name.empty()9
)
180
67
    CombinedArg = true;
181
182
71
  StringRef Dirs(DirList);
183
71
  if (Dirs.empty()) // Empty string should not add '.'.
184
0
    return;
185
186
71
  StringRef::size_type Delim;
187
74
  while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
188
3
    if (Delim == 0) { // Leading colon.
189
0
      if (CombinedArg) {
190
0
        CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
191
0
      } else {
192
0
        CmdArgs.push_back(ArgName);
193
0
        CmdArgs.push_back(".");
194
0
      }
195
3
    } else {
196
3
      if (CombinedArg) {
197
1
        CmdArgs.push_back(
198
1
            Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
199
2
      } else {
200
2
        CmdArgs.push_back(ArgName);
201
2
        CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
202
2
      }
203
3
    }
204
3
    Dirs = Dirs.substr(Delim + 1);
205
3
  }
206
207
71
  if (Dirs.empty()) { // Trailing colon.
208
0
    if (CombinedArg) {
209
0
      CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
210
0
    } else {
211
0
      CmdArgs.push_back(ArgName);
212
0
      CmdArgs.push_back(".");
213
0
    }
214
71
  } else { // Add the last path.
215
71
    if (CombinedArg) {
216
67
      CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
217
67
    } else {
218
4
      CmdArgs.push_back(ArgName);
219
4
      CmdArgs.push_back(Args.MakeArgString(Dirs));
220
4
    }
221
71
  }
222
71
}
223
224
void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
225
                            const ArgList &Args, ArgStringList &CmdArgs,
226
6.43k
                            const JobAction &JA) {
227
6.43k
  const Driver &D = TC.getDriver();
228
229
  // Add extra linker input arguments which are not treated as inputs
230
  // (constructed via -Xarch_).
231
6.43k
  Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
232
233
  // LIBRARY_PATH are included before user inputs and only supported on native
234
  // toolchains.
235
6.43k
  if (!TC.isCrossCompiling())
236
4.56k
    addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
237
238
8.07k
  for (const auto &II : Inputs) {
239
    // If the current tool chain refers to an OpenMP offloading host, we
240
    // should ignore inputs that refer to OpenMP offloading devices -
241
    // they will be embedded according to a proper linker script.
242
8.07k
    if (auto *IA = II.getAction())
243
8.07k
      if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
244
8.07k
           
IA->isDeviceOffloading(Action::OFK_OpenMP)155
))
245
0
        continue;
246
247
8.07k
    if (!TC.HasNativeLLVMSupport() && 
types::isLLVMIR(II.getType())693
)
248
      // Don't try to pass LLVM inputs unless we have native support.
249
4
      D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
250
251
    // Add filenames immediately.
252
8.07k
    if (II.isFilename()) {
253
6.93k
      CmdArgs.push_back(II.getFilename());
254
6.93k
      continue;
255
6.93k
    }
256
257
    // Otherwise, this is a linker input argument.
258
1.14k
    const Arg &A = II.getInputArg();
259
260
    // Handle reserved library options.
261
1.14k
    if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
262
4
      TC.AddCXXStdlibLibArgs(Args, CmdArgs);
263
1.13k
    else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
264
2
      TC.AddCCKextLibArgs(Args, CmdArgs);
265
1.13k
    else if (A.getOption().matches(options::OPT_z)) {
266
      // Pass -z prefix for gcc linker compatibility.
267
3
      A.claim();
268
3
      A.render(Args, CmdArgs);
269
1.13k
    } else if (A.getOption().matches(options::OPT_b)) {
270
3
      const llvm::Triple &T = TC.getTriple();
271
3
      if (!T.isOSAIX()) {
272
1
        TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
273
1
            << A.getSpelling() << T.str();
274
1
      }
275
      // Pass -b prefix for AIX linker.
276
3
      A.claim();
277
3
      A.render(Args, CmdArgs);
278
1.12k
    } else {
279
1.12k
      A.renderAsInput(Args, CmdArgs);
280
1.12k
    }
281
1.14k
  }
282
6.43k
}
283
284
void tools::addLinkerCompressDebugSectionsOption(
285
    const ToolChain &TC, const llvm::opt::ArgList &Args,
286
2.02k
    llvm::opt::ArgStringList &CmdArgs) {
287
  // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi
288
  // whereas zlib is an alias to zlib-gabi. Therefore -gz=none|zlib|zlib-gnu
289
  // are translated to --compress-debug-sections=none|zlib|zlib-gnu.
290
  // -gz is not translated since ld --compress-debug-sections option requires an
291
  // argument.
292
2.02k
  if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) {
293
17
    StringRef V = A->getValue();
294
17
    if (V == "none" || 
V == "zlib"13
||
V == "zlib-gnu"4
)
295
17
      CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V));
296
0
    else
297
0
      TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
298
0
          << A->getOption().getName() << V;
299
17
  }
300
2.02k
}
301
302
void tools::AddTargetFeature(const ArgList &Args,
303
                             std::vector<StringRef> &Features,
304
                             OptSpecifier OnOpt, OptSpecifier OffOpt,
305
7.99k
                             StringRef FeatureName) {
306
7.99k
  if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
307
126
    if (A->getOption().matches(OnOpt))
308
97
      Features.push_back(Args.MakeArgString("+" + FeatureName));
309
29
    else
310
29
      Features.push_back(Args.MakeArgString("-" + FeatureName));
311
126
  }
312
7.99k
}
313
314
/// Get the (LLVM) name of the AMDGPU gpu we are targeting.
315
static std::string getAMDGPUTargetGPU(const llvm::Triple &T,
316
830
                                      const ArgList &Args) {
317
830
  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
318
784
    auto GPUName = getProcessorFromTargetID(T, A->getValue());
319
784
    return llvm::StringSwitch<std::string>(GPUName)
320
784
        .Cases("rv630", "rv635", "r600")
321
784
        .Cases("rv610", "rv620", "rs780", "rs880")
322
784
        .Case("rv740", "rv770")
323
784
        .Case("palm", "cedar")
324
784
        .Cases("sumo", "sumo2", "sumo")
325
784
        .Case("hemlock", "cypress")
326
784
        .Case("aruba", "cayman")
327
784
        .Default(GPUName.str());
328
784
  }
329
46
  return "";
330
830
}
331
332
3
static std::string getLanaiTargetCPU(const ArgList &Args) {
333
3
  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
334
0
    return A->getValue();
335
0
  }
336
3
  return "";
337
3
}
338
339
/// Get the (LLVM) name of the WebAssembly cpu we are targeting.
340
79
static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
341
  // If we have -mcpu=, use that.
342
79
  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
343
6
    StringRef CPU = A->getValue();
344
345
#ifdef __wasm__
346
    // Handle "native" by examining the host. "native" isn't meaningful when
347
    // cross compiling, so only support this when the host is also WebAssembly.
348
    if (CPU == "native")
349
      return llvm::sys::getHostCPUName();
350
#endif
351
352
6
    return CPU;
353
6
  }
354
355
73
  return "generic";
356
79
}
357
358
std::string tools::getCPUName(const Driver &D, const ArgList &Args,
359
46.9k
                              const llvm::Triple &T, bool FromAs) {
360
46.9k
  Arg *A;
361
362
46.9k
  switch (T.getArch()) {
363
87
  default:
364
87
    return "";
365
366
1.16k
  case llvm::Triple::aarch64:
367
1.16k
  case llvm::Triple::aarch64_32:
368
1.34k
  case llvm::Triple::aarch64_be:
369
1.34k
    return aarch64::getAArch64TargetCPU(Args, T, A);
370
371
2.07k
  case llvm::Triple::arm:
372
2.39k
  case llvm::Triple::armeb:
373
3.53k
  case llvm::Triple::thumb:
374
3.74k
  case llvm::Triple::thumbeb: {
375
3.74k
    StringRef MArch, MCPU;
376
3.74k
    arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
377
3.74k
    return arm::getARMTargetCPU(MCPU, MArch, T);
378
3.53k
  }
379
380
216
  case llvm::Triple::avr:
381
216
    if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
382
193
      return A->getValue();
383
23
    return "";
384
385
30
  case llvm::Triple::m68k:
386
30
    return m68k::getM68kTargetCPU(Args);
387
388
420
  case llvm::Triple::mips:
389
613
  case llvm::Triple::mipsel:
390
799
  case llvm::Triple::mips64:
391
941
  case llvm::Triple::mips64el: {
392
941
    StringRef CPUName;
393
941
    StringRef ABIName;
394
941
    mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
395
941
    return std::string(CPUName);
396
799
  }
397
398
30
  case llvm::Triple::nvptx:
399
300
  case llvm::Triple::nvptx64:
400
300
    if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
401
300
      return A->getValue();
402
0
    return "";
403
404
147
  case llvm::Triple::ppc:
405
155
  case llvm::Triple::ppcle:
406
350
  case llvm::Triple::ppc64:
407
570
  case llvm::Triple::ppc64le: {
408
570
    std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
409
    // LLVM may default to generating code for the native CPU,
410
    // but, like gcc, we default to a more generic option for
411
    // each architecture. (except on AIX)
412
570
    if (!TargetCPUName.empty())
413
153
      return TargetCPUName;
414
415
417
    if (T.isOSAIX())
416
110
      TargetCPUName = "pwr7";
417
307
    else if (T.getArch() == llvm::Triple::ppc64le)
418
160
      TargetCPUName = "ppc64le";
419
147
    else if (T.getArch() == llvm::Triple::ppc64)
420
87
      TargetCPUName = "ppc64";
421
60
    else
422
60
      TargetCPUName = "ppc";
423
424
417
    return TargetCPUName;
425
570
  }
426
246
  case llvm::Triple::riscv32:
427
429
  case llvm::Triple::riscv64:
428
429
    if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
429
21
      return A->getValue();
430
408
    return "";
431
432
20
  case llvm::Triple::bpfel:
433
23
  case llvm::Triple::bpfeb:
434
183
  case llvm::Triple::sparc:
435
208
  case llvm::Triple::sparcel:
436
299
  case llvm::Triple::sparcv9:
437
299
    if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
438
134
      return A->getValue();
439
165
    if (T.getArch() == llvm::Triple::sparc && 
T.isOSSolaris()80
)
440
19
      return "v9";
441
146
    return "";
442
443
10.4k
  case llvm::Triple::x86:
444
37.9k
  case llvm::Triple::x86_64:
445
37.9k
    return x86::getX86TargetCPU(D, Args, T);
446
447
98
  case llvm::Triple::hexagon:
448
98
    return "hexagon" +
449
98
           toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
450
451
3
  case llvm::Triple::lanai:
452
3
    return getLanaiTargetCPU(Args);
453
454
67
  case llvm::Triple::systemz:
455
67
    return systemz::getSystemZTargetCPU(Args);
456
457
54
  case llvm::Triple::r600:
458
830
  case llvm::Triple::amdgcn:
459
830
    return getAMDGPUTargetGPU(T, Args);
460
461
61
  case llvm::Triple::wasm32:
462
79
  case llvm::Triple::wasm64:
463
79
    return std::string(getWebAssemblyTargetCPU(Args));
464
46.9k
  }
465
46.9k
}
466
467
3.96k
llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
468
3.96k
  Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
469
3.96k
  if (!LtoJobsArg)
470
3.96k
    return {};
471
3
  if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue()))
472
0
    D.Diag(diag::err_drv_invalid_int_value)
473
0
        << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
474
3
  return LtoJobsArg->getValue();
475
3.96k
}
476
477
// CloudABI uses -ffunction-sections and -fdata-sections by default.
478
43.6k
bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
479
43.6k
  return Triple.getOS() == llvm::Triple::CloudABI;
480
43.6k
}
481
482
void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
483
                          ArgStringList &CmdArgs, const InputInfo &Output,
484
300
                          const InputInfo &Input, bool IsThinLTO) {
485
300
  const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
486
300
  const Driver &D = ToolChain.getDriver();
487
300
  if (llvm::sys::path::filename(Linker) != "ld.lld" &&
488
300
      
llvm::sys::path::stem(Linker) != "ld.lld"66
) {
489
    // Tell the linker to load the plugin. This has to come before
490
    // AddLinkerInputs as gold requires -plugin to come before any -plugin-opt
491
    // that -Wl might forward.
492
66
    CmdArgs.push_back("-plugin");
493
494
#if defined(_WIN32)
495
    const char *Suffix = ".dll";
496
#elif defined(__APPLE__)
497
66
    const char *Suffix = ".dylib";
498
#else
499
    const char *Suffix = ".so";
500
#endif
501
502
66
    SmallString<1024> Plugin;
503
66
    llvm::sys::path::native(
504
66
        Twine(D.Dir) + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" + Suffix,
505
66
        Plugin);
506
66
    CmdArgs.push_back(Args.MakeArgString(Plugin));
507
66
  }
508
509
  // Try to pass driver level flags relevant to LTO code generation down to
510
  // the plugin.
511
512
  // Handle flags for selecting CPU variants.
513
300
  std::string CPU = getCPUName(D, Args, ToolChain.getTriple());
514
300
  if (!CPU.empty())
515
300
    CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
516
517
300
  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
518
    // The optimization level matches
519
    // CompilerInvocation.cpp:getOptimizationLevel().
520
18
    StringRef OOpt;
521
18
    if (A->getOption().matches(options::OPT_O4) ||
522
18
        A->getOption().matches(options::OPT_Ofast))
523
1
      OOpt = "3";
524
17
    else if (A->getOption().matches(options::OPT_O)) {
525
16
      OOpt = A->getValue();
526
16
      if (OOpt == "g")
527
2
        OOpt = "1";
528
14
      else if (OOpt == "s" || 
OOpt == "z"12
)
529
4
        OOpt = "2";
530
16
    } else 
if (1
A->getOption().matches(options::OPT_O0)1
)
531
1
      OOpt = "0";
532
18
    if (!OOpt.empty())
533
18
      CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
534
18
  }
535
536
300
  if (Args.hasArg(options::OPT_gsplit_dwarf)) {
537
7
    CmdArgs.push_back(
538
7
        Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
539
7
            Output.getFilename() + "_dwo"));
540
7
  }
541
542
300
  if (IsThinLTO)
543
25
    CmdArgs.push_back("-plugin-opt=thinlto");
544
545
300
  StringRef Parallelism = getLTOParallelism(Args, D);
546
300
  if (!Parallelism.empty())
547
2
    CmdArgs.push_back(
548
2
        Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
549
550
  // If an explicit debugger tuning argument appeared, pass it along.
551
300
  if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
552
300
                               options::OPT_ggdbN_Group)) {
553
10
    if (A->getOption().matches(options::OPT_glldb))
554
2
      CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
555
8
    else if (A->getOption().matches(options::OPT_gsce))
556
0
      CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
557
8
    else if (A->getOption().matches(options::OPT_gdbx))
558
0
      CmdArgs.push_back("-plugin-opt=-debugger-tune=dbx");
559
8
    else
560
8
      CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
561
10
  }
562
563
300
  bool UseSeparateSections =
564
300
      isUseSeparateSections(ToolChain.getEffectiveTriple());
565
566
300
  if (Args.hasFlag(options::OPT_ffunction_sections,
567
300
                   options::OPT_fno_function_sections, UseSeparateSections)) {
568
1
    CmdArgs.push_back("-plugin-opt=-function-sections");
569
1
  }
570
571
300
  if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
572
300
                   UseSeparateSections)) {
573
1
    CmdArgs.push_back("-plugin-opt=-data-sections");
574
1
  }
575
576
300
  if (Arg *A = getLastProfileSampleUseArg(Args)) {
577
1
    StringRef FName = A->getValue();
578
1
    if (!llvm::sys::fs::exists(FName))
579
0
      D.Diag(diag::err_drv_no_such_file) << FName;
580
1
    else
581
1
      CmdArgs.push_back(
582
1
          Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
583
1
  }
584
585
300
  auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
586
300
                                           options::OPT_fcs_profile_generate_EQ,
587
300
                                           options::OPT_fno_profile_generate);
588
300
  if (CSPGOGenerateArg &&
589
300
      
CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate)0
)
590
0
    CSPGOGenerateArg = nullptr;
591
592
300
  auto *ProfileUseArg = getLastProfileUseArg(Args);
593
594
300
  if (CSPGOGenerateArg) {
595
0
    CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate"));
596
0
    if (CSPGOGenerateArg->getOption().matches(
597
0
            options::OPT_fcs_profile_generate_EQ)) {
598
0
      SmallString<128> Path(CSPGOGenerateArg->getValue());
599
0
      llvm::sys::path::append(Path, "default_%m.profraw");
600
0
      CmdArgs.push_back(
601
0
          Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path));
602
0
    } else
603
0
      CmdArgs.push_back(
604
0
          Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw"));
605
300
  } else if (ProfileUseArg) {
606
1
    SmallString<128> Path(
607
1
        ProfileUseArg->getNumValues() == 0 ? "" : 
ProfileUseArg->getValue()0
);
608
1
    if (Path.empty() || 
llvm::sys::fs::is_directory(Path)0
)
609
1
      llvm::sys::path::append(Path, "default.profdata");
610
1
    CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") +
611
1
                                         Path));
612
1
  }
613
614
  // Pass an option to enable/disable the new pass manager.
615
300
  if (auto *A = Args.getLastArg(options::OPT_flegacy_pass_manager,
616
300
                                options::OPT_fno_legacy_pass_manager)) {
617
4
    if (A->getOption().matches(options::OPT_flegacy_pass_manager))
618
2
      CmdArgs.push_back("-plugin-opt=legacy-pass-manager");
619
2
    else
620
2
      CmdArgs.push_back("-plugin-opt=new-pass-manager");
621
4
  }
622
623
  // Pass an option to enable pseudo probe emission.
624
300
  if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
625
300
                   options::OPT_fno_pseudo_probe_for_profiling, false))
626
3
    CmdArgs.push_back("-plugin-opt=pseudo-probe-for-profiling");
627
628
  // Setup statistics file output.
629
300
  SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
630
300
  if (!StatsFile.empty())
631
2
    CmdArgs.push_back(
632
2
        Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
633
634
300
  addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true);
635
636
  // Handle remark diagnostics on screen options: '-Rpass-*'.
637
300
  renderRpassOptions(Args, CmdArgs);
638
639
  // Handle serialized remarks options: '-fsave-optimization-record'
640
  // and '-foptimization-record-*'.
641
300
  if (willEmitRemarks(Args))
642
3
    renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input,
643
3
                         Output);
644
645
  // Handle remarks hotness/threshold related options.
646
300
  renderRemarksHotnessOptions(Args, CmdArgs);
647
648
300
  addMachineOutlinerArgs(D, Args, CmdArgs, ToolChain.getEffectiveTriple(),
649
300
                         /*IsLTO=*/true);
650
300
}
651
652
void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
653
198
                                 ArgStringList &CmdArgs) {
654
  // Enable -frtlib-add-rpath by default for the case of VE.
655
198
  const bool IsVE = TC.getTriple().isVE();
656
198
  bool DefaultValue = IsVE;
657
198
  if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
658
198
                    options::OPT_fno_rtlib_add_rpath, DefaultValue))
659
194
    return;
660
661
4
  std::string CandidateRPath = TC.getArchSpecificLibPath();
662
4
  if (TC.getVFS().exists(CandidateRPath)) {
663
4
    CmdArgs.push_back("-rpath");
664
4
    CmdArgs.push_back(Args.MakeArgString(CandidateRPath));
665
4
  }
666
4
}
667
668
bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
669
                             const ArgList &Args, bool ForceStaticHostRuntime,
670
5.58k
                             bool IsOffloadingHost, bool GompNeedsRT) {
671
5.58k
  if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
672
5.58k
                    options::OPT_fno_openmp, false))
673
5.42k
    return false;
674
675
153
  Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
676
677
153
  if (RTKind == Driver::OMPRT_Unknown)
678
    // Already diagnosed.
679
2
    return false;
680
681
151
  if (ForceStaticHostRuntime)
682
12
    CmdArgs.push_back("-Bstatic");
683
684
151
  switch (RTKind) {
685
124
  case Driver::OMPRT_OMP:
686
124
    CmdArgs.push_back("-lomp");
687
124
    break;
688
14
  case Driver::OMPRT_GOMP:
689
14
    CmdArgs.push_back("-lgomp");
690
14
    break;
691
13
  case Driver::OMPRT_IOMP5:
692
13
    CmdArgs.push_back("-liomp5");
693
13
    break;
694
0
  case Driver::OMPRT_Unknown:
695
0
    break;
696
151
  }
697
698
151
  if (ForceStaticHostRuntime)
699
12
    CmdArgs.push_back("-Bdynamic");
700
701
151
  if (RTKind == Driver::OMPRT_GOMP && 
GompNeedsRT14
)
702
6
      CmdArgs.push_back("-lrt");
703
704
151
  if (IsOffloadingHost)
705
19
    CmdArgs.push_back("-lomptarget");
706
707
151
  addArchSpecificRPath(TC, Args, CmdArgs);
708
709
151
  return true;
710
151
}
711
712
static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
713
                                ArgStringList &CmdArgs, StringRef Sanitizer,
714
402
                                bool IsShared, bool IsWhole) {
715
  // Wrap any static runtimes that must be forced into executable in
716
  // whole-archive.
717
402
  if (IsWhole) 
CmdArgs.push_back("--whole-archive")343
;
718
402
  CmdArgs.push_back(TC.getCompilerRTArgString(
719
402
      Args, Sanitizer, IsShared ? 
ToolChain::FT_Shared47
:
ToolChain::FT_Static355
));
720
402
  if (IsWhole) 
CmdArgs.push_back("--no-whole-archive")343
;
721
722
402
  if (IsShared) {
723
47
    addArchSpecificRPath(TC, Args, CmdArgs);
724
47
  }
725
402
}
726
727
// Tries to use a file with the list of dynamic symbols that need to be exported
728
// from the runtime library. Returns true if the file was found.
729
static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
730
                                    ArgStringList &CmdArgs,
731
328
                                    StringRef Sanitizer) {
732
  // Solaris ld defaults to --export-dynamic behaviour but doesn't support
733
  // the option, so don't try to pass it.
734
328
  if (TC.getTriple().getOS() == llvm::Triple::Solaris)
735
2
    return true;
736
326
  SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
737
326
  if (llvm::sys::fs::exists(SanRT + ".syms")) {
738
20
    CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
739
20
    return true;
740
20
  }
741
306
  return false;
742
326
}
743
744
5.98k
static const char *getAsNeededOption(const ToolChain &TC, bool as_needed) {
745
5.98k
  assert(!TC.getTriple().isOSAIX() &&
746
5.98k
         "AIX linker does not support any form of --as-needed option yet.");
747
748
  // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
749
  // for the native forms -z ignore/-z record, they are missing in Illumos,
750
  // so always use the native form.
751
5.98k
  if (TC.getTriple().isOSSolaris())
752
2
    return as_needed ? 
"-zignore"0
: "-zrecord";
753
5.98k
  else
754
5.98k
    return as_needed ? 
"--as-needed"2.83k
:
"--no-as-needed"3.14k
;
755
5.98k
}
756
757
void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
758
314
                                     ArgStringList &CmdArgs) {
759
  // Fuchsia never needs these.  Any sanitizer runtimes with system
760
  // dependencies use the `.deplibs` feature instead.
761
314
  if (TC.getTriple().isOSFuchsia())
762
2
    return;
763
764
  // Force linking against the system libraries sanitizers depends on
765
  // (see PR15823 why this is necessary).
766
312
  CmdArgs.push_back(getAsNeededOption(TC, false));
767
  // There's no libpthread or librt on RTEMS & Android.
768
312
  if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
769
312
      
!TC.getTriple().isAndroid()311
) {
770
308
    CmdArgs.push_back("-lpthread");
771
308
    if (!TC.getTriple().isOSOpenBSD())
772
308
      CmdArgs.push_back("-lrt");
773
308
  }
774
312
  CmdArgs.push_back("-lm");
775
  // There's no libdl on all OSes.
776
312
  if (!TC.getTriple().isOSFreeBSD() && 
!TC.getTriple().isOSNetBSD()308
&&
777
312
      
!TC.getTriple().isOSOpenBSD()290
&&
778
312
      
TC.getTriple().getOS() != llvm::Triple::RTEMS290
)
779
289
    CmdArgs.push_back("-ldl");
780
  // Required for backtrace on some OSes
781
312
  if (TC.getTriple().isOSFreeBSD() ||
782
312
      
TC.getTriple().isOSNetBSD()308
||
783
312
      
TC.getTriple().isOSOpenBSD()290
)
784
22
    CmdArgs.push_back("-lexecinfo");
785
312
}
786
787
static void
788
collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
789
                         SmallVectorImpl<StringRef> &SharedRuntimes,
790
                         SmallVectorImpl<StringRef> &StaticRuntimes,
791
                         SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
792
                         SmallVectorImpl<StringRef> &HelperStaticRuntimes,
793
2.10k
                         SmallVectorImpl<StringRef> &RequiredSymbols) {
794
2.10k
  const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
795
  // Collect shared runtimes.
796
2.10k
  if (SanArgs.needsSharedRt()) {
797
229
    if (SanArgs.needsAsanRt() && 
SanArgs.linkRuntimes()24
) {
798
24
      SharedRuntimes.push_back("asan");
799
24
      if (!Args.hasArg(options::OPT_shared) && 
!TC.getTriple().isAndroid()21
)
800
13
        HelperStaticRuntimes.push_back("asan-preinit");
801
24
    }
802
229
    if (SanArgs.needsMemProfRt() && 
SanArgs.linkRuntimes()0
) {
803
0
      SharedRuntimes.push_back("memprof");
804
0
      if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
805
0
        HelperStaticRuntimes.push_back("memprof-preinit");
806
0
    }
807
229
    if (SanArgs.needsUbsanRt() && 
SanArgs.linkRuntimes()7
) {
808
7
      if (SanArgs.requiresMinimalRuntime())
809
0
        SharedRuntimes.push_back("ubsan_minimal");
810
7
      else
811
7
        SharedRuntimes.push_back("ubsan_standalone");
812
7
    }
813
229
    if (SanArgs.needsScudoRt() && 
SanArgs.linkRuntimes()7
) {
814
7
      if (SanArgs.requiresMinimalRuntime())
815
0
        SharedRuntimes.push_back("scudo_minimal");
816
7
      else
817
7
        SharedRuntimes.push_back("scudo");
818
7
    }
819
229
    if (SanArgs.needsTsanRt() && 
SanArgs.linkRuntimes()0
)
820
0
      SharedRuntimes.push_back("tsan");
821
229
    if (SanArgs.needsHwasanRt() && 
SanArgs.linkRuntimes()9
) {
822
9
      if (SanArgs.needsHwasanAliasesRt())
823
0
        SharedRuntimes.push_back("hwasan_aliases");
824
9
      else
825
9
        SharedRuntimes.push_back("hwasan");
826
9
    }
827
229
  }
828
829
  // The stats_client library is also statically linked into DSOs.
830
2.10k
  if (SanArgs.needsStatsRt() && 
SanArgs.linkRuntimes()1
)
831
1
    StaticRuntimes.push_back("stats_client");
832
833
  // Collect static runtimes.
834
2.10k
  if (Args.hasArg(options::OPT_shared)) {
835
    // Don't link static runtimes into DSOs.
836
73
    return;
837
73
  }
838
839
  // Each static runtime that has a DSO counterpart above is excluded below,
840
  // but runtimes that exist only as static are not affected by needsSharedRt.
841
842
2.02k
  if (!SanArgs.needsSharedRt() && 
SanArgs.needsAsanRt()1.82k
&&
SanArgs.linkRuntimes()86
) {
843
85
    StaticRuntimes.push_back("asan");
844
85
    if (SanArgs.linkCXXRuntimes())
845
2
      StaticRuntimes.push_back("asan_cxx");
846
85
  }
847
848
2.02k
  if (!SanArgs.needsSharedRt() && 
SanArgs.needsMemProfRt()1.82k
&&
849
2.02k
      
SanArgs.linkRuntimes()2
) {
850
2
    StaticRuntimes.push_back("memprof");
851
2
    if (SanArgs.linkCXXRuntimes())
852
2
      StaticRuntimes.push_back("memprof_cxx");
853
2
  }
854
855
2.02k
  if (!SanArgs.needsSharedRt() && 
SanArgs.needsHwasanRt()1.82k
&&
SanArgs.linkRuntimes()16
) {
856
16
    if (SanArgs.needsHwasanAliasesRt()) {
857
1
      StaticRuntimes.push_back("hwasan_aliases");
858
1
      if (SanArgs.linkCXXRuntimes())
859
0
        StaticRuntimes.push_back("hwasan_aliases_cxx");
860
15
    } else {
861
15
      StaticRuntimes.push_back("hwasan");
862
15
      if (SanArgs.linkCXXRuntimes())
863
0
        StaticRuntimes.push_back("hwasan_cxx");
864
15
    }
865
16
  }
866
2.02k
  if (SanArgs.needsDfsanRt() && 
SanArgs.linkRuntimes()4
)
867
4
    StaticRuntimes.push_back("dfsan");
868
2.02k
  if (SanArgs.needsLsanRt() && 
SanArgs.linkRuntimes()27
)
869
26
    StaticRuntimes.push_back("lsan");
870
2.02k
  if (SanArgs.needsMsanRt() && 
SanArgs.linkRuntimes()34
) {
871
33
    StaticRuntimes.push_back("msan");
872
33
    if (SanArgs.linkCXXRuntimes())
873
2
      StaticRuntimes.push_back("msan_cxx");
874
33
  }
875
2.02k
  if (!SanArgs.needsSharedRt() && 
SanArgs.needsTsanRt()1.82k
&&
876
2.02k
      
SanArgs.linkRuntimes()23
) {
877
22
    StaticRuntimes.push_back("tsan");
878
22
    if (SanArgs.linkCXXRuntimes())
879
2
      StaticRuntimes.push_back("tsan_cxx");
880
22
  }
881
2.02k
  if (!SanArgs.needsSharedRt() && 
SanArgs.needsUbsanRt()1.82k
&&
SanArgs.linkRuntimes()93
) {
882
92
    if (SanArgs.requiresMinimalRuntime()) {
883
7
      StaticRuntimes.push_back("ubsan_minimal");
884
85
    } else {
885
85
      StaticRuntimes.push_back("ubsan_standalone");
886
85
      if (SanArgs.linkCXXRuntimes())
887
2
        StaticRuntimes.push_back("ubsan_standalone_cxx");
888
85
    }
889
92
  }
890
2.02k
  if (SanArgs.needsSafeStackRt() && 
SanArgs.linkRuntimes()11
) {
891
11
    NonWholeStaticRuntimes.push_back("safestack");
892
11
    RequiredSymbols.push_back("__safestack_init");
893
11
  }
894
2.02k
  if (!(SanArgs.needsSharedRt() && 
SanArgs.needsUbsanRt()200
&&
SanArgs.linkRuntimes()6
)) {
895
2.02k
    if (SanArgs.needsCfiRt() && 
SanArgs.linkRuntimes()1
)
896
1
      StaticRuntimes.push_back("cfi");
897
2.02k
    if (SanArgs.needsCfiDiagRt() && 
SanArgs.linkRuntimes()1
) {
898
1
      StaticRuntimes.push_back("cfi_diag");
899
1
      if (SanArgs.linkCXXRuntimes())
900
0
        StaticRuntimes.push_back("ubsan_standalone_cxx");
901
1
    }
902
2.02k
  }
903
2.02k
  if (SanArgs.needsStatsRt() && 
SanArgs.linkRuntimes()1
) {
904
1
    NonWholeStaticRuntimes.push_back("stats");
905
1
    RequiredSymbols.push_back("__sanitizer_stats_register");
906
1
  }
907
2.02k
  if (!SanArgs.needsSharedRt() && 
SanArgs.needsScudoRt()1.82k
&&
SanArgs.linkRuntimes()23
) {
908
23
    if (SanArgs.requiresMinimalRuntime()) {
909
3
      StaticRuntimes.push_back("scudo_minimal");
910
3
      if (SanArgs.linkCXXRuntimes())
911
0
        StaticRuntimes.push_back("scudo_cxx_minimal");
912
20
    } else {
913
20
      StaticRuntimes.push_back("scudo");
914
20
      if (SanArgs.linkCXXRuntimes())
915
0
        StaticRuntimes.push_back("scudo_cxx");
916
20
    }
917
23
  }
918
2.02k
}
919
920
// Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
921
// C runtime, etc). Returns true if sanitizer system deps need to be linked in.
922
bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
923
2.10k
                                 ArgStringList &CmdArgs) {
924
2.10k
  SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
925
2.10k
      NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
926
2.10k
  collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
927
2.10k
                           NonWholeStaticRuntimes, HelperStaticRuntimes,
928
2.10k
                           RequiredSymbols);
929
930
2.10k
  const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
931
  // Inject libfuzzer dependencies.
932
2.10k
  if (SanArgs.needsFuzzer() && 
SanArgs.linkRuntimes()7
&&
933
2.10k
      
!Args.hasArg(options::OPT_shared)7
) {
934
935
7
    addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
936
7
    if (SanArgs.needsFuzzerInterceptors())
937
7
      addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
938
7
                          true);
939
7
    if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
940
7
      bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
941
7
                                 
!Args.hasArg(options::OPT_static)2
;
942
7
      if (OnlyLibstdcxxStatic)
943
2
        CmdArgs.push_back("-Bstatic");
944
7
      TC.AddCXXStdlibLibArgs(Args, CmdArgs);
945
7
      if (OnlyLibstdcxxStatic)
946
2
        CmdArgs.push_back("-Bdynamic");
947
7
    }
948
7
  }
949
950
2.10k
  for (auto RT : SharedRuntimes)
951
47
    addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
952
2.10k
  for (auto RT : HelperStaticRuntimes)
953
13
    addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
954
2.10k
  bool AddExportDynamic = false;
955
2.10k
  for (auto RT : StaticRuntimes) {
956
316
    addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
957
316
    AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
958
316
  }
959
2.10k
  for (auto RT : NonWholeStaticRuntimes) {
960
12
    addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
961
12
    AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
962
12
  }
963
2.10k
  for (auto S : RequiredSymbols) {
964
12
    CmdArgs.push_back("-u");
965
12
    CmdArgs.push_back(Args.MakeArgString(S));
966
12
  }
967
  // If there is a static runtime with no dynamic list, force all the symbols
968
  // to be dynamic to be sure we export sanitizer interface functions.
969
2.10k
  if (AddExportDynamic)
970
297
    CmdArgs.push_back("--export-dynamic");
971
972
2.10k
  if (SanArgs.hasCrossDsoCfi() && 
!AddExportDynamic4
)
973
2
    CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
974
975
2.10k
  return !StaticRuntimes.empty() || 
!NonWholeStaticRuntimes.empty()1.79k
;
976
2.10k
}
977
978
1.99k
bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
979
1.99k
  if (Args.hasArg(options::OPT_shared))
980
68
    return false;
981
982
1.92k
  if (TC.getXRayArgs().needsXRayRt()) {
983
2
    CmdArgs.push_back("-whole-archive");
984
2
    CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
985
2
    for (const auto &Mode : TC.getXRayArgs().modeList())
986
2
      CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
987
2
    CmdArgs.push_back("-no-whole-archive");
988
2
    return true;
989
2
  }
990
991
1.92k
  return false;
992
1.92k
}
993
994
2
void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
995
2
  CmdArgs.push_back(getAsNeededOption(TC, false));
996
2
  CmdArgs.push_back("-lpthread");
997
2
  if (!TC.getTriple().isOSOpenBSD())
998
2
    CmdArgs.push_back("-lrt");
999
2
  CmdArgs.push_back("-lm");
1000
1001
2
  if (!TC.getTriple().isOSFreeBSD() &&
1002
2
      !TC.getTriple().isOSNetBSD() &&
1003
2
      !TC.getTriple().isOSOpenBSD())
1004
2
    CmdArgs.push_back("-ldl");
1005
2
}
1006
1007
5.77k
bool tools::areOptimizationsEnabled(const ArgList &Args) {
1008
  // Find the last -O arg and see if it is non-zero.
1009
5.77k
  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1010
263
    return !A->getOption().matches(options::OPT_O0);
1011
  // Defaults to -O0.
1012
5.51k
  return false;
1013
5.77k
}
1014
1015
const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
1016
                                  const InputInfo &Input,
1017
40
                                  const InputInfo &Output) {
1018
40
  auto AddPostfix = [JA](auto &F) {
1019
38
    if (JA.getOffloadingDeviceKind() == Action::OFK_HIP)
1020
8
      F += (Twine("_") + JA.getOffloadingArch()).str();
1021
38
    F += ".dwo";
1022
38
  };
1023
40
  if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
1024
7
    if (StringRef(A->getValue()) == "single")
1025
2
      return Args.MakeArgString(Output.getFilename());
1026
1027
38
  Arg *FinalOutput = Args.getLastArg(options::OPT_o);
1028
38
  if (FinalOutput && 
Args.hasArg(options::OPT_c)4
) {
1029
2
    SmallString<128> T(FinalOutput->getValue());
1030
2
    llvm::sys::path::remove_filename(T);
1031
2
    llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue()));
1032
2
    AddPostfix(T);
1033
2
    return Args.MakeArgString(T);
1034
36
  } else {
1035
    // Use the compilation dir.
1036
36
    Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
1037
36
                             options::OPT_fdebug_compilation_dir_EQ);
1038
36
    SmallString<128> T(A ? 
A->getValue()0
: "");
1039
36
    SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
1040
36
    AddPostfix(F);
1041
36
    T += F;
1042
36
    return Args.MakeArgString(T);
1043
36
  }
1044
38
}
1045
1046
void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
1047
                           const JobAction &JA, const ArgList &Args,
1048
1
                           const InputInfo &Output, const char *OutFile) {
1049
1
  ArgStringList ExtractArgs;
1050
1
  ExtractArgs.push_back("--extract-dwo");
1051
1052
1
  ArgStringList StripArgs;
1053
1
  StripArgs.push_back("--strip-dwo");
1054
1055
  // Grabbing the output of the earlier compile step.
1056
1
  StripArgs.push_back(Output.getFilename());
1057
1
  ExtractArgs.push_back(Output.getFilename());
1058
1
  ExtractArgs.push_back(OutFile);
1059
1060
1
  const char *Exec =
1061
1
      Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
1062
1
  InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1063
1064
  // First extract the dwo sections.
1065
1
  C.addCommand(std::make_unique<Command>(JA, T,
1066
1
                                         ResponseFileSupport::AtFileCurCP(),
1067
1
                                         Exec, ExtractArgs, II, Output));
1068
1069
  // Then remove them from the original .o file.
1070
1
  C.addCommand(std::make_unique<Command>(
1071
1
      JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
1072
1
}
1073
1074
// Claim options we don't want to warn if they are unused. We do this for
1075
// options that build systems might add but are unused when assembling or only
1076
// running the preprocessor for example.
1077
44.2k
void tools::claimNoWarnArgs(const ArgList &Args) {
1078
  // Don't warn about unused -f(no-)?lto.  This can happen when we're
1079
  // preprocessing, precompiling or assembling.
1080
44.2k
  Args.ClaimAllArgs(options::OPT_flto_EQ);
1081
44.2k
  Args.ClaimAllArgs(options::OPT_flto);
1082
44.2k
  Args.ClaimAllArgs(options::OPT_fno_lto);
1083
44.2k
}
1084
1085
42.8k
Arg *tools::getLastProfileUseArg(const ArgList &Args) {
1086
42.8k
  auto *ProfileUseArg = Args.getLastArg(
1087
42.8k
      options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
1088
42.8k
      options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
1089
42.8k
      options::OPT_fno_profile_instr_use);
1090
1091
42.8k
  if (ProfileUseArg &&
1092
42.8k
      
ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use)58
)
1093
4
    ProfileUseArg = nullptr;
1094
1095
42.8k
  return ProfileUseArg;
1096
42.8k
}
1097
1098
43.2k
Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
1099
43.2k
  auto *ProfileSampleUseArg = Args.getLastArg(
1100
43.2k
      options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
1101
43.2k
      options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
1102
43.2k
      options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
1103
1104
43.2k
  if (ProfileSampleUseArg &&
1105
43.2k
      
(10
ProfileSampleUseArg->getOption().matches(
1106
10
           options::OPT_fno_profile_sample_use) ||
1107
10
       
ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)8
))
1108
2
    return nullptr;
1109
1110
43.2k
  return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
1111
43.2k
                         options::OPT_fauto_profile_EQ);
1112
43.2k
}
1113
1114
/// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
1115
/// smooshes them together with platform defaults, to decide whether
1116
/// this compile should be using PIC mode or not. Returns a tuple of
1117
/// (RelocationModel, PICLevel, IsPIE).
1118
std::tuple<llvm::Reloc::Model, unsigned, bool>
1119
45.0k
tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
1120
45.0k
  const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
1121
45.0k
  const llvm::Triple &Triple = ToolChain.getTriple();
1122
1123
45.0k
  bool PIE = ToolChain.isPIEDefault();
1124
45.0k
  bool PIC = PIE || 
ToolChain.isPICDefault()44.5k
;
1125
  // The Darwin/MachO default to use PIC does not apply when using -static.
1126
45.0k
  if (Triple.isOSBinFormatMachO() && 
Args.hasArg(options::OPT_static)16.4k
)
1127
26
    PIE = PIC = false;
1128
45.0k
  bool IsPICLevelTwo = PIC;
1129
1130
45.0k
  bool KernelOrKext =
1131
45.0k
      Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1132
1133
  // Android-specific defaults for PIC/PIE
1134
45.0k
  if (Triple.isAndroid()) {
1135
255
    switch (Triple.getArch()) {
1136
98
    case llvm::Triple::arm:
1137
98
    case llvm::Triple::armeb:
1138
100
    case llvm::Triple::thumb:
1139
100
    case llvm::Triple::thumbeb:
1140
154
    case llvm::Triple::aarch64:
1141
154
    case llvm::Triple::mips:
1142
198
    case llvm::Triple::mipsel:
1143
198
    case llvm::Triple::mips64:
1144
218
    case llvm::Triple::mips64el:
1145
218
      PIC = true; // "-fpic"
1146
218
      break;
1147
1148
22
    case llvm::Triple::x86:
1149
37
    case llvm::Triple::x86_64:
1150
37
      PIC = true; // "-fPIC"
1151
37
      IsPICLevelTwo = true;
1152
37
      break;
1153
1154
0
    default:
1155
0
      break;
1156
255
    }
1157
255
  }
1158
1159
  // OpenBSD-specific defaults for PIE
1160
45.0k
  if (Triple.isOSOpenBSD()) {
1161
117
    switch (ToolChain.getArch()) {
1162
11
    case llvm::Triple::arm:
1163
20
    case llvm::Triple::aarch64:
1164
32
    case llvm::Triple::mips64:
1165
44
    case llvm::Triple::mips64el:
1166
83
    case llvm::Triple::x86:
1167
102
    case llvm::Triple::x86_64:
1168
102
      IsPICLevelTwo = false; // "-fpie"
1169
102
      break;
1170
1171
4
    case llvm::Triple::ppc:
1172
8
    case llvm::Triple::sparcv9:
1173
8
      IsPICLevelTwo = true; // "-fPIE"
1174
8
      break;
1175
1176
7
    default:
1177
7
      break;
1178
117
    }
1179
117
  }
1180
1181
  // AMDGPU-specific defaults for PIC.
1182
45.0k
  if (Triple.getArch() == llvm::Triple::amdgcn)
1183
612
    PIC = true;
1184
1185
  // The last argument relating to either PIC or PIE wins, and no
1186
  // other argument is used. If the last argument is any flavor of the
1187
  // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1188
  // option implicitly enables PIC at the same level.
1189
45.0k
  Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1190
45.0k
                                    options::OPT_fpic, options::OPT_fno_pic,
1191
45.0k
                                    options::OPT_fPIE, options::OPT_fno_PIE,
1192
45.0k
                                    options::OPT_fpie, options::OPT_fno_pie);
1193
45.0k
  if (Triple.isOSWindows() && 
LastPICArg8.06k
&&
1194
45.0k
      LastPICArg ==
1195
48
          Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1196
48
                          options::OPT_fPIE, options::OPT_fpie)) {
1197
24
    ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1198
24
        << LastPICArg->getSpelling() << Triple.str();
1199
24
    if (Triple.getArch() == llvm::Triple::x86_64)
1200
12
      return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1201
12
    return std::make_tuple(llvm::Reloc::Static, 0U, false);
1202
24
  }
1203
1204
  // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1205
  // is forced, then neither PIC nor PIE flags will have no effect.
1206
45.0k
  if (!ToolChain.isPICDefaultForced()) {
1207
20.8k
    if (LastPICArg) {
1208
303
      Option O = LastPICArg->getOption();
1209
303
      if (O.matches(options::OPT_fPIC) || 
O.matches(options::OPT_fpic)178
||
1210
303
          
O.matches(options::OPT_fPIE)154
||
O.matches(options::OPT_fpie)136
) {
1211
181
        PIE = O.matches(options::OPT_fPIE) || 
O.matches(options::OPT_fpie)163
;
1212
181
        PIC =
1213
181
            PIE || 
O.matches(options::OPT_fPIC)149
||
O.matches(options::OPT_fpic)24
;
1214
181
        IsPICLevelTwo =
1215
181
            O.matches(options::OPT_fPIE) || 
O.matches(options::OPT_fPIC)163
;
1216
181
      } else {
1217
122
        PIE = PIC = false;
1218
122
        if (EffectiveTriple.isPS4CPU()) {
1219
20
          Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1220
20
          StringRef Model = ModelArg ? 
ModelArg->getValue()4
:
""16
;
1221
20
          if (Model != "kernel") {
1222
16
            PIC = true;
1223
16
            ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
1224
16
                << LastPICArg->getSpelling();
1225
16
          }
1226
20
        }
1227
122
      }
1228
303
    }
1229
20.8k
  }
1230
1231
  // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
1232
  // PIC level would've been set to level 1, force it back to level 2 PIC
1233
  // instead.
1234
45.0k
  if (PIC && 
(26.2k
Triple.isOSDarwin()26.2k
||
EffectiveTriple.isPS4CPU()9.80k
))
1235
16.5k
    IsPICLevelTwo |= ToolChain.isPICDefault();
1236
1237
  // This kernel flags are a trump-card: they will disable PIC/PIE
1238
  // generation, independent of the argument order.
1239
45.0k
  if (KernelOrKext &&
1240
45.0k
      
(27
(27
!EffectiveTriple.isiOS()27
||
EffectiveTriple.isOSVersionLT(6)8
) &&
1241
27
       
!EffectiveTriple.isWatchOS()23
))
1242
22
    PIC = PIE = false;
1243
1244
45.0k
  if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1245
    // This is a very special mode. It trumps the other modes, almost no one
1246
    // uses it, and it isn't even valid on any OS but Darwin.
1247
8
    if (!Triple.isOSDarwin())
1248
2
      ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1249
2
          << A->getSpelling() << Triple.str();
1250
1251
    // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1252
1253
    // Only a forced PIC mode can cause the actual compile to have PIC defines
1254
    // etc., no flags are sufficient. This behavior was selected to closely
1255
    // match that of llvm-gcc and Apple GCC before that.
1256
8
    PIC = ToolChain.isPICDefault() && 
ToolChain.isPICDefaultForced()7
;
1257
1258
8
    return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 
2U3
:
0U5
, false);
1259
8
  }
1260
1261
45.0k
  bool EmbeddedPISupported;
1262
45.0k
  switch (Triple.getArch()) {
1263
1.74k
    case llvm::Triple::arm:
1264
1.88k
    case llvm::Triple::armeb:
1265
1.93k
    case llvm::Triple::thumb:
1266
1.95k
    case llvm::Triple::thumbeb:
1267
1.95k
      EmbeddedPISupported = true;
1268
1.95k
      break;
1269
43.0k
    default:
1270
43.0k
      EmbeddedPISupported = false;
1271
43.0k
      break;
1272
45.0k
  }
1273
1274
45.0k
  bool ROPI = false, RWPI = false;
1275
45.0k
  Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1276
45.0k
  if (LastROPIArg && 
LastROPIArg->getOption().matches(options::OPT_fropi)19
) {
1277
19
    if (!EmbeddedPISupported)
1278
2
      ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1279
2
          << LastROPIArg->getSpelling() << Triple.str();
1280
19
    ROPI = true;
1281
19
  }
1282
45.0k
  Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1283
45.0k
  if (LastRWPIArg && 
LastRWPIArg->getOption().matches(options::OPT_frwpi)14
) {
1284
14
    if (!EmbeddedPISupported)
1285
2
      ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1286
2
          << LastRWPIArg->getSpelling() << Triple.str();
1287
14
    RWPI = true;
1288
14
  }
1289
1290
  // ROPI and RWPI are not compatible with PIC or PIE.
1291
45.0k
  if ((ROPI || 
RWPI45.0k
) &&
(26
PIC26
||
PIE23
))
1292
3
    ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1293
1294
45.0k
  if (Triple.isMIPS()) {
1295
1.43k
    StringRef CPUName;
1296
1.43k
    StringRef ABIName;
1297
1.43k
    mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1298
    // When targeting the N64 ABI, PIC is the default, except in the case
1299
    // when the -mno-abicalls option is used. In that case we exit
1300
    // at next check regardless of PIC being set below.
1301
1.43k
    if (ABIName == "n64")
1302
402
      PIC = true;
1303
    // When targettng MIPS with -mno-abicalls, it's always static.
1304
1.43k
    if(Args.hasArg(options::OPT_mno_abicalls))
1305
77
      return std::make_tuple(llvm::Reloc::Static, 0U, false);
1306
    // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1307
    // does not use PIC level 2 for historical reasons.
1308
1.35k
    IsPICLevelTwo = false;
1309
1.35k
  }
1310
1311
44.9k
  if (PIC)
1312
26.2k
    return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 
2U24.9k
:
1U1.28k
, PIE);
1313
1314
18.7k
  llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1315
18.7k
  if (ROPI && 
RWPI17
)
1316
6
    RelocM = llvm::Reloc::ROPI_RWPI;
1317
18.7k
  else if (ROPI)
1318
11
    RelocM = llvm::Reloc::ROPI;
1319
18.6k
  else if (RWPI)
1320
6
    RelocM = llvm::Reloc::RWPI;
1321
1322
18.7k
  return std::make_tuple(RelocM, 0U, false);
1323
44.9k
}
1324
1325
// `-falign-functions` indicates that the functions should be aligned to a
1326
// 16-byte boundary.
1327
//
1328
// `-falign-functions=1` is the same as `-fno-align-functions`.
1329
//
1330
// The scalar `n` in `-falign-functions=n` must be an integral value between
1331
// [0, 65536].  If the value is not a power-of-two, it will be rounded up to
1332
// the nearest power-of-two.
1333
//
1334
// If we return `0`, the frontend will default to the backend's preferred
1335
// alignment.
1336
//
1337
// NOTE: icc only allows values between [0, 4096].  icc uses `-falign-functions`
1338
// to mean `-falign-functions=16`.  GCC defaults to the backend's preferred
1339
// alignment.  For unaligned functions, we default to the backend's preferred
1340
// alignment.
1341
unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1342
43.3k
                                       const ArgList &Args) {
1343
43.3k
  const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1344
43.3k
                                 options::OPT_falign_functions_EQ,
1345
43.3k
                                 options::OPT_fno_align_functions);
1346
43.3k
  if (!A || 
A->getOption().matches(options::OPT_fno_align_functions)8
)
1347
43.3k
    return 0;
1348
1349
18.4E
  if (A->getOption().matches(options::OPT_falign_functions))
1350
1
    return 0;
1351
1352
18.4E
  unsigned Value = 0;
1353
18.4E
  if (StringRef(A->getValue()).getAsInteger(10, Value) || 
Value > 655365
)
1354
2
    TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1355
2
        << A->getAsString(Args) << A->getValue();
1356
18.4E
  return Value ? 
llvm::Log2_32_Ceil(std::min(Value, 65536u))5
:
Value18.4E
;
1357
18.4E
}
1358
1359
unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC,
1360
43.8k
                                         const ArgList &Args) {
1361
43.8k
  const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
1362
1363
43.8k
  if (!A)
1364
43.8k
    return 0;
1365
1366
20
  unsigned Value = 0;
1367
20
  if (StringRef(A->getValue()).getAsInteger(10, Value) || 
Value > 515
||
1368
20
      
Value < 215
)
1369
0
    TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1370
0
        << A->getAsString(Args) << A->getValue();
1371
20
  return Value;
1372
43.8k
}
1373
1374
void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1375
220
                             ArgStringList &CmdArgs) {
1376
220
  llvm::Reloc::Model RelocationModel;
1377
220
  unsigned PICLevel;
1378
220
  bool IsPIE;
1379
220
  std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1380
1381
220
  if (RelocationModel != llvm::Reloc::Static)
1382
36
    CmdArgs.push_back("-KPIC");
1383
220
}
1384
1385
/// Determine whether Objective-C automated reference counting is
1386
/// enabled.
1387
47.0k
bool tools::isObjCAutoRefCount(const ArgList &Args) {
1388
47.0k
  return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1389
47.0k
}
1390
1391
enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
1392
1393
static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
1394
6.40k
                                const ArgList &Args) {
1395
6.40k
  if (Args.hasArg(options::OPT_static_libgcc) ||
1396
6.40k
      
Args.hasArg(options::OPT_static)6.38k
||
Args.hasArg(options::OPT_static_pie)6.34k
)
1397
70
    return LibGccType::StaticLibGcc;
1398
6.33k
  if (Args.hasArg(options::OPT_shared_libgcc))
1399
10
    return LibGccType::SharedLibGcc;
1400
  // The Android NDK only provides libunwind.a, not libunwind.so.
1401
6.32k
  if (TC.getTriple().isAndroid())
1402
306
    return LibGccType::StaticLibGcc;
1403
  // For MinGW, don't imply a shared libgcc here, we only want to return
1404
  // SharedLibGcc if that was explicitly requested.
1405
6.02k
  if (D.CCCIsCXX() && 
!TC.getTriple().isOSCygMing()143
)
1406
141
    return LibGccType::SharedLibGcc;
1407
5.88k
  return LibGccType::UnspecifiedLibGcc;
1408
6.02k
}
1409
1410
// Gcc adds libgcc arguments in various ways:
1411
//
1412
// gcc <none>:     -lgcc --as-needed -lgcc_s --no-as-needed
1413
// g++ <none>:                       -lgcc_s               -lgcc
1414
// gcc shared:                       -lgcc_s               -lgcc
1415
// g++ shared:                       -lgcc_s               -lgcc
1416
// gcc static:     -lgcc             -lgcc_eh
1417
// g++ static:     -lgcc             -lgcc_eh
1418
// gcc static-pie: -lgcc             -lgcc_eh
1419
// g++ static-pie: -lgcc             -lgcc_eh
1420
//
1421
// Also, certain targets need additional adjustments.
1422
1423
static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
1424
3.61k
                             ArgStringList &CmdArgs, const ArgList &Args) {
1425
3.61k
  ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
1426
  // Targets that don't use unwind libraries.
1427
3.61k
  if ((TC.getTriple().isAndroid() && 
UNW == ToolChain::UNW_Libgcc316
) ||
1428
3.61k
      TC.getTriple().isOSIAMCU() || 
TC.getTriple().isOSBinFormatWasm()3.60k
||
1429
3.61k
      
UNW == ToolChain::UNW_None3.56k
)
1430
318
    return;
1431
1432
3.29k
  LibGccType LGT = getLibGccType(TC, D, Args);
1433
3.29k
  bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
1434
3.29k
                  
!TC.getTriple().isAndroid()2.86k
&&
1435
3.29k
                  
!TC.getTriple().isOSCygMing()2.86k
&&
!TC.getTriple().isOSAIX()2.86k
;
1436
3.29k
  if (AsNeeded)
1437
2.83k
    CmdArgs.push_back(getAsNeededOption(TC, true));
1438
1439
3.29k
  switch (UNW) {
1440
0
  case ToolChain::UNW_None:
1441
0
    return;
1442
2.91k
  case ToolChain::UNW_Libgcc: {
1443
2.91k
    if (LGT == LibGccType::StaticLibGcc)
1444
23
      CmdArgs.push_back("-lgcc_eh");
1445
2.89k
    else
1446
2.89k
      CmdArgs.push_back("-lgcc_s");
1447
2.91k
    break;
1448
0
  }
1449
375
  case ToolChain::UNW_CompilerRT:
1450
375
    if (TC.getTriple().isOSAIX()) {
1451
      // AIX only has libunwind as a shared library. So do not pass
1452
      // anything in if -static is specified.
1453
45
      if (LGT != LibGccType::StaticLibGcc)
1454
44
        CmdArgs.push_back("-lunwind");
1455
330
    } else if (LGT == LibGccType::StaticLibGcc) {
1456
320
      CmdArgs.push_back("-l:libunwind.a");
1457
320
    } else 
if (10
TC.getTriple().isOSCygMing()10
) {
1458
6
      if (LGT == LibGccType::SharedLibGcc)
1459
2
        CmdArgs.push_back("-l:libunwind.dll.a");
1460
4
      else
1461
        // Let the linker choose between libunwind.dll.a and libunwind.a
1462
        // depending on what's available, and depending on the -static flag
1463
4
        CmdArgs.push_back("-lunwind");
1464
6
    } else {
1465
4
      CmdArgs.push_back("-l:libunwind.so");
1466
4
    }
1467
375
    break;
1468
3.29k
  }
1469
1470
3.29k
  if (AsNeeded)
1471
2.83k
    CmdArgs.push_back(getAsNeededOption(TC, false));
1472
3.29k
}
1473
1474
static void AddLibgcc(const ToolChain &TC, const Driver &D,
1475
3.11k
                      ArgStringList &CmdArgs, const ArgList &Args) {
1476
3.11k
  LibGccType LGT = getLibGccType(TC, D, Args);
1477
3.11k
  if (LGT != LibGccType::SharedLibGcc)
1478
3.04k
    CmdArgs.push_back("-lgcc");
1479
3.11k
  AddUnwindLibrary(TC, D, CmdArgs, Args);
1480
3.11k
  if (LGT == LibGccType::SharedLibGcc)
1481
68
    CmdArgs.push_back("-lgcc");
1482
3.11k
}
1483
1484
void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1485
3.99k
                           ArgStringList &CmdArgs, const ArgList &Args) {
1486
  // Make use of compiler-rt if --rtlib option is used
1487
3.99k
  ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1488
1489
3.99k
  switch (RLT) {
1490
497
  case ToolChain::RLT_CompilerRT:
1491
497
    CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1492
497
    AddUnwindLibrary(TC, D, CmdArgs, Args);
1493
497
    break;
1494
3.49k
  case ToolChain::RLT_Libgcc:
1495
    // Make sure libgcc is not used under MSVC environment by default
1496
3.49k
    if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1497
      // Issue error diagnostic if libgcc is explicitly specified
1498
      // through command line as --rtlib option argument.
1499
382
      if (Args.hasArg(options::OPT_rtlib_EQ)) {
1500
5
        TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1501
5
            << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1502
5
      }
1503
382
    } else
1504
3.11k
      AddLibgcc(TC, D, CmdArgs, Args);
1505
3.49k
    break;
1506
3.99k
  }
1507
1508
  // On Android, the unwinder uses dl_iterate_phdr (or one of
1509
  // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
1510
  // statically-linked executables, these functions come from libc.a instead.
1511
3.99k
  if (TC.getTriple().isAndroid() && 
!Args.hasArg(options::OPT_static)316
&&
1512
3.99k
      
!Args.hasArg(options::OPT_static_pie)306
)
1513
306
    CmdArgs.push_back("-ldl");
1514
3.99k
}
1515
1516
SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1517
                                         const InputInfo &Output,
1518
                                         const InputInfo &Input,
1519
47.3k
                                         const Driver &D) {
1520
47.3k
  const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1521
47.3k
  if (!A)
1522
47.3k
    return {};
1523
1524
8
  StringRef SaveStats = A->getValue();
1525
8
  SmallString<128> StatsFile;
1526
8
  if (SaveStats == "obj" && 
Output.isFilename()4
) {
1527
4
    StatsFile.assign(Output.getFilename());
1528
4
    llvm::sys::path::remove_filename(StatsFile);
1529
4
  } else if (SaveStats != "cwd") {
1530
1
    D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1531
1
    return {};
1532
1
  }
1533
1534
7
  StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1535
7
  llvm::sys::path::append(StatsFile, BaseName);
1536
7
  llvm::sys::path::replace_extension(StatsFile, "stats");
1537
7
  return StatsFile;
1538
8
}
1539
1540
void tools::addMultilibFlag(bool Enabled, const char *const Flag,
1541
5.87k
                            Multilib::flags_list &Flags) {
1542
5.87k
  Flags.push_back(std::string(Enabled ? 
"+"1.57k
:
"-"4.29k
) + Flag);
1543
5.87k
}
1544
1545
void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
1546
37.6k
                                  ArgStringList &CmdArgs, bool IsLTO) {
1547
37.6k
  auto addArg = [&, IsLTO](const Twine &Arg) {
1548
25
    if (IsLTO) {
1549
4
      CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
1550
21
    } else {
1551
21
      CmdArgs.push_back("-mllvm");
1552
21
      CmdArgs.push_back(Args.MakeArgString(Arg));
1553
21
    }
1554
25
  };
1555
1556
37.6k
  if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
1557
5
    addArg(Twine("-x86-branches-within-32B-boundaries"));
1558
5
  }
1559
37.6k
  if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
1560
6
    StringRef Value = A->getValue();
1561
6
    unsigned Boundary;
1562
6
    if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
1563
6
        
!llvm::isPowerOf2_64(Boundary)4
) {
1564
2
      D.Diag(diag::err_drv_invalid_argument_to_option)
1565
2
          << Value << A->getOption().getName();
1566
4
    } else {
1567
4
      addArg("-x86-align-branch-boundary=" + Twine(Boundary));
1568
4
    }
1569
6
  }
1570
37.6k
  if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
1571
11
    std::string AlignBranch;
1572
39
    for (StringRef T : A->getValues()) {
1573
39
      if (T != "fused" && 
T != "jcc"28
&&
T != "jmp"19
&&
T != "call"10
&&
1574
39
          
T != "ret"8
&&
T != "indirect"6
)
1575
4
        D.Diag(diag::err_drv_invalid_malign_branch_EQ)
1576
4
            << T << "fused, jcc, jmp, call, ret, indirect";
1577
39
      if (!AlignBranch.empty())
1578
28
        AlignBranch += '+';
1579
39
      AlignBranch += T;
1580
39
    }
1581
11
    addArg("-x86-align-branch=" + Twine(AlignBranch));
1582
11
  }
1583
37.6k
  if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
1584
5
    StringRef Value = A->getValue();
1585
5
    unsigned PrefixSize;
1586
5
    if (Value.getAsInteger(10, PrefixSize)) {
1587
0
      D.Diag(diag::err_drv_invalid_argument_to_option)
1588
0
          << Value << A->getOption().getName();
1589
5
    } else {
1590
5
      addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
1591
5
    }
1592
5
  }
1593
37.6k
}
1594
1595
static llvm::opt::Arg *
1596
1.19k
getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
1597
  // The last of -mcode-object-v3, -mno-code-object-v3 and
1598
  // -mcode-object-version=<version> wins.
1599
1.19k
  return Args.getLastArg(options::OPT_mcode_object_v3_legacy,
1600
1.19k
                         options::OPT_mno_code_object_v3_legacy,
1601
1.19k
                         options::OPT_mcode_object_version_EQ);
1602
1.19k
}
1603
1604
void tools::checkAMDGPUCodeObjectVersion(const Driver &D,
1605
396
                                         const llvm::opt::ArgList &Args) {
1606
396
  const unsigned MinCodeObjVer = 2;
1607
396
  const unsigned MaxCodeObjVer = 4;
1608
1609
  // Emit warnings for legacy options even if they are overridden.
1610
396
  if (Args.hasArg(options::OPT_mno_code_object_v3_legacy))
1611
6
    D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3"
1612
6
                                          << "-mcode-object-version=2";
1613
1614
396
  if (Args.hasArg(options::OPT_mcode_object_v3_legacy))
1615
6
    D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3"
1616
6
                                          << "-mcode-object-version=3";
1617
1618
396
  if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
1619
14
    if (CodeObjArg->getOption().getID() ==
1620
14
        options::OPT_mcode_object_version_EQ) {
1621
6
      unsigned CodeObjVer = MaxCodeObjVer;
1622
6
      auto Remnant =
1623
6
          StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
1624
6
      if (Remnant || CodeObjVer < MinCodeObjVer || 
CodeObjVer > MaxCodeObjVer5
)
1625
1
        D.Diag(diag::err_drv_invalid_int_value)
1626
1
            << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
1627
6
    }
1628
14
  }
1629
396
}
1630
1631
unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D,
1632
192
                                           const llvm::opt::ArgList &Args) {
1633
192
  unsigned CodeObjVer = 4; // default
1634
192
  if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
1635
22
    if (CodeObjArg->getOption().getID() ==
1636
22
        options::OPT_mno_code_object_v3_legacy) {
1637
4
      CodeObjVer = 2;
1638
18
    } else if (CodeObjArg->getOption().getID() ==
1639
18
               options::OPT_mcode_object_v3_legacy) {
1640
6
      CodeObjVer = 3;
1641
12
    } else {
1642
12
      StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
1643
12
    }
1644
22
  }
1645
192
  return CodeObjVer;
1646
192
}
1647
1648
bool tools::haveAMDGPUCodeObjectVersionArgument(
1649
608
    const Driver &D, const llvm::opt::ArgList &Args) {
1650
608
  return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
1651
608
}
1652
1653
void tools::addMachineOutlinerArgs(const Driver &D,
1654
                                   const llvm::opt::ArgList &Args,
1655
                                   llvm::opt::ArgStringList &CmdArgs,
1656
43.6k
                                   const llvm::Triple &Triple, bool IsLTO) {
1657
43.6k
  auto addArg = [&, IsLTO](const Twine &Arg) {
1658
8
    if (IsLTO) {
1659
2
      CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
1660
6
    } else {
1661
6
      CmdArgs.push_back("-mllvm");
1662
6
      CmdArgs.push_back(Args.MakeArgString(Arg));
1663
6
    }
1664
8
  };
1665
1666
43.6k
  if (Arg *A = Args.getLastArg(options::OPT_moutline,
1667
43.6k
                               options::OPT_mno_outline)) {
1668
9
    if (A->getOption().matches(options::OPT_moutline)) {
1669
      // We only support -moutline in AArch64 and ARM targets right now. If
1670
      // we're not compiling for these, emit a warning and ignore the flag.
1671
      // Otherwise, add the proper mllvm flags.
1672
5
      if (!(Triple.isARM() || 
Triple.isThumb()2
||
1673
5
            
Triple.getArch() == llvm::Triple::aarch642
||
1674
5
            
Triple.getArch() == llvm::Triple::aarch64_321
)) {
1675
1
        D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
1676
4
      } else {
1677
4
        addArg(Twine("-enable-machine-outliner"));
1678
4
      }
1679
5
    } else {
1680
      // Disable all outlining behaviour.
1681
4
      addArg(Twine("-enable-machine-outliner=never"));
1682
4
    }
1683
9
  }
1684
43.6k
}
1685
1686
void tools::addOpenMPDeviceRTL(const Driver &D,
1687
                               const llvm::opt::ArgList &DriverArgs,
1688
                               llvm::opt::ArgStringList &CC1Args,
1689
                               StringRef BitcodeSuffix,
1690
34
                               const llvm::Triple &Triple) {
1691
34
  SmallVector<StringRef, 8> LibraryPaths;
1692
1693
  // Add path to clang lib / lib64 folder.
1694
34
  SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
1695
34
  llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
1696
34
  LibraryPaths.emplace_back(DefaultLibPath.c_str());
1697
1698
  // Add user defined library paths from LIBRARY_PATH.
1699
34
  llvm::Optional<std::string> LibPath =
1700
34
      llvm::sys::Process::GetEnv("LIBRARY_PATH");
1701
34
  if (LibPath) {
1702
3
    SmallVector<StringRef, 8> Frags;
1703
3
    const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
1704
3
    llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
1705
3
    for (StringRef Path : Frags)
1706
3
      LibraryPaths.emplace_back(Path.trim());
1707
3
  }
1708
1709
34
  OptSpecifier LibomptargetBCPathOpt =
1710
34
      Triple.isAMDGCN() ? 
options::OPT_libomptarget_amdgcn_bc_path_EQ13
1711
34
                        : 
options::OPT_libomptarget_nvptx_bc_path_EQ21
;
1712
1713
34
  StringRef ArchPrefix = Triple.isAMDGCN() ? 
"amdgcn"13
:
"nvptx"21
;
1714
34
  std::string LibOmpTargetName = "libomptarget-" + BitcodeSuffix.str() + ".bc";
1715
1716
  // First check whether user specifies bc library
1717
34
  if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) {
1718
19
    SmallString<128> LibOmpTargetFile(A->getValue());
1719
19
    if (llvm::sys::fs::exists(LibOmpTargetFile) &&
1720
19
        
llvm::sys::fs::is_directory(LibOmpTargetFile)16
) {
1721
9
      llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
1722
9
    }
1723
1724
19
    if (llvm::sys::fs::exists(LibOmpTargetFile)) {
1725
16
      CC1Args.push_back("-mlink-builtin-bitcode");
1726
16
      CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
1727
16
    } else {
1728
3
      D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
1729
3
          << LibOmpTargetFile;
1730
3
    }
1731
19
  } else {
1732
15
    bool FoundBCLibrary = false;
1733
1734
18
    for (StringRef LibraryPath : LibraryPaths) {
1735
18
      SmallString<128> LibOmpTargetFile(LibraryPath);
1736
18
      llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
1737
18
      if (llvm::sys::fs::exists(LibOmpTargetFile)) {
1738
3
        CC1Args.push_back("-mlink-builtin-bitcode");
1739
3
        CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
1740
3
        FoundBCLibrary = true;
1741
3
        break;
1742
3
      }
1743
18
    }
1744
1745
15
    if (!FoundBCLibrary)
1746
12
      D.Diag(diag::err_drv_omp_offload_target_missingbcruntime)
1747
12
          << LibOmpTargetName << ArchPrefix;
1748
15
  }
1749
34
}