Coverage Report

Created: 2020-09-22 08:39

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