Coverage Report

Created: 2019-07-24 05:18

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