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