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