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