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