Coverage Report

Created: 2020-02-15 09:57

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