xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/CommonArgs.cpp (revision 972a253a57b6f144b0e4a3e2080a2a0076ec55a0)
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 "HIPAMD.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/SmallSet.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/ADT/StringSwitch.h"
41 #include "llvm/ADT/Twine.h"
42 #include "llvm/Config/llvm-config.h"
43 #include "llvm/Option/Arg.h"
44 #include "llvm/Option/ArgList.h"
45 #include "llvm/Option/Option.h"
46 #include "llvm/Support/CodeGen.h"
47 #include "llvm/Support/Compression.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/FileSystem.h"
51 #include "llvm/Support/Host.h"
52 #include "llvm/Support/Path.h"
53 #include "llvm/Support/Process.h"
54 #include "llvm/Support/Program.h"
55 #include "llvm/Support/ScopedPrinter.h"
56 #include "llvm/Support/TargetParser.h"
57 #include "llvm/Support/Threading.h"
58 #include "llvm/Support/VirtualFileSystem.h"
59 #include "llvm/Support/YAMLParser.h"
60 
61 using namespace clang::driver;
62 using namespace clang::driver::tools;
63 using namespace clang;
64 using namespace llvm::opt;
65 
66 static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs) {
67   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
68     CmdArgs.push_back(Args.MakeArgString(Twine("--plugin-opt=-pass-remarks=") +
69                                          A->getValue()));
70 
71   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
72     CmdArgs.push_back(Args.MakeArgString(
73         Twine("--plugin-opt=-pass-remarks-missed=") + A->getValue()));
74 
75   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
76     CmdArgs.push_back(Args.MakeArgString(
77         Twine("--plugin-opt=-pass-remarks-analysis=") + A->getValue()));
78 }
79 
80 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
81                                  const llvm::Triple &Triple,
82                                  const InputInfo &Input,
83                                  const InputInfo &Output) {
84   StringRef Format = "yaml";
85   if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
86     Format = A->getValue();
87 
88   SmallString<128> F;
89   const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
90   if (A)
91     F = A->getValue();
92   else if (Output.isFilename())
93     F = Output.getFilename();
94 
95   assert(!F.empty() && "Cannot determine remarks output name.");
96   // Append "opt.ld.<format>" to the end of the file name.
97   CmdArgs.push_back(
98       Args.MakeArgString(Twine("--plugin-opt=opt-remarks-filename=") + F +
99                          Twine(".opt.ld.") + Format));
100 
101   if (const Arg *A =
102           Args.getLastArg(options::OPT_foptimization_record_passes_EQ))
103     CmdArgs.push_back(Args.MakeArgString(
104         Twine("--plugin-opt=opt-remarks-passes=") + A->getValue()));
105 
106   CmdArgs.push_back(Args.MakeArgString(
107       Twine("--plugin-opt=opt-remarks-format=") + Format.data()));
108 }
109 
110 static void renderRemarksHotnessOptions(const ArgList &Args,
111                                         ArgStringList &CmdArgs) {
112   if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
113                    options::OPT_fno_diagnostics_show_hotness, false))
114     CmdArgs.push_back("--plugin-opt=opt-remarks-with-hotness");
115 
116   if (const Arg *A =
117           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ))
118     CmdArgs.push_back(Args.MakeArgString(
119         Twine("--plugin-opt=opt-remarks-hotness-threshold=") + A->getValue()));
120 }
121 
122 void tools::addPathIfExists(const Driver &D, const Twine &Path,
123                             ToolChain::path_list &Paths) {
124   if (D.getVFS().exists(Path))
125     Paths.push_back(Path.str());
126 }
127 
128 void tools::handleTargetFeaturesGroup(const ArgList &Args,
129                                       std::vector<StringRef> &Features,
130                                       OptSpecifier Group) {
131   for (const Arg *A : Args.filtered(Group)) {
132     StringRef Name = A->getOption().getName();
133     A->claim();
134 
135     // Skip over "-m".
136     assert(Name.startswith("m") && "Invalid feature name.");
137     Name = Name.substr(1);
138 
139     bool IsNegative = Name.startswith("no-");
140     if (IsNegative)
141       Name = Name.substr(3);
142     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
143   }
144 }
145 
146 SmallVector<StringRef>
147 tools::unifyTargetFeatures(ArrayRef<StringRef> Features) {
148   // Only add a feature if it hasn't been seen before starting from the end.
149   SmallVector<StringRef> UnifiedFeatures;
150   llvm::DenseSet<StringRef> UsedFeatures;
151   for (StringRef Feature : llvm::reverse(Features)) {
152     if (UsedFeatures.insert(Feature.drop_front()).second)
153       UnifiedFeatures.insert(UnifiedFeatures.begin(), Feature);
154   }
155 
156   return UnifiedFeatures;
157 }
158 
159 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
160                              const char *ArgName, const char *EnvVar) {
161   const char *DirList = ::getenv(EnvVar);
162   bool CombinedArg = false;
163 
164   if (!DirList)
165     return; // Nothing to do.
166 
167   StringRef Name(ArgName);
168   if (Name.equals("-I") || Name.equals("-L") || Name.empty())
169     CombinedArg = true;
170 
171   StringRef Dirs(DirList);
172   if (Dirs.empty()) // Empty string should not add '.'.
173     return;
174 
175   StringRef::size_type Delim;
176   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
177     if (Delim == 0) { // Leading colon.
178       if (CombinedArg) {
179         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
180       } else {
181         CmdArgs.push_back(ArgName);
182         CmdArgs.push_back(".");
183       }
184     } else {
185       if (CombinedArg) {
186         CmdArgs.push_back(
187             Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
188       } else {
189         CmdArgs.push_back(ArgName);
190         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
191       }
192     }
193     Dirs = Dirs.substr(Delim + 1);
194   }
195 
196   if (Dirs.empty()) { // Trailing colon.
197     if (CombinedArg) {
198       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
199     } else {
200       CmdArgs.push_back(ArgName);
201       CmdArgs.push_back(".");
202     }
203   } else { // Add the last path.
204     if (CombinedArg) {
205       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
206     } else {
207       CmdArgs.push_back(ArgName);
208       CmdArgs.push_back(Args.MakeArgString(Dirs));
209     }
210   }
211 }
212 
213 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
214                             const ArgList &Args, ArgStringList &CmdArgs,
215                             const JobAction &JA) {
216   const Driver &D = TC.getDriver();
217 
218   // Add extra linker input arguments which are not treated as inputs
219   // (constructed via -Xarch_).
220   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
221 
222   // LIBRARY_PATH are included before user inputs and only supported on native
223   // toolchains.
224   if (!TC.isCrossCompiling())
225     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
226 
227   for (const auto &II : Inputs) {
228     // If the current tool chain refers to an OpenMP offloading host, we
229     // should ignore inputs that refer to OpenMP offloading devices -
230     // they will be embedded according to a proper linker script.
231     if (auto *IA = II.getAction())
232       if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
233            IA->isDeviceOffloading(Action::OFK_OpenMP)))
234         continue;
235 
236     if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
237       // Don't try to pass LLVM inputs unless we have native support.
238       D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
239 
240     // Add filenames immediately.
241     if (II.isFilename()) {
242       CmdArgs.push_back(II.getFilename());
243       continue;
244     }
245 
246     // In some error cases, the input could be Nothing; skip those.
247     if (II.isNothing())
248       continue;
249 
250     // Otherwise, this is a linker input argument.
251     const Arg &A = II.getInputArg();
252 
253     // Handle reserved library options.
254     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
255       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
256     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
257       TC.AddCCKextLibArgs(Args, CmdArgs);
258     else if (A.getOption().matches(options::OPT_z)) {
259       // Pass -z prefix for gcc linker compatibility.
260       A.claim();
261       A.render(Args, CmdArgs);
262     } else if (A.getOption().matches(options::OPT_b)) {
263       const llvm::Triple &T = TC.getTriple();
264       if (!T.isOSAIX()) {
265         TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
266             << A.getSpelling() << T.str();
267       }
268       // Pass -b prefix for AIX linker.
269       A.claim();
270       A.render(Args, CmdArgs);
271     } else {
272       A.renderAsInput(Args, CmdArgs);
273     }
274   }
275 }
276 
277 void tools::addLinkerCompressDebugSectionsOption(
278     const ToolChain &TC, const llvm::opt::ArgList &Args,
279     llvm::opt::ArgStringList &CmdArgs) {
280   // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi
281   // whereas zlib is an alias to zlib-gabi and zlib-gnu is obsoleted. Therefore
282   // -gz=none|zlib are translated to --compress-debug-sections=none|zlib. -gz
283   // is not translated since ld --compress-debug-sections option requires an
284   // argument.
285   if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) {
286     StringRef V = A->getValue();
287     if (V == "none" || V == "zlib")
288       CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V));
289     else
290       TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
291           << A->getOption().getName() << V;
292   }
293 }
294 
295 void tools::AddTargetFeature(const ArgList &Args,
296                              std::vector<StringRef> &Features,
297                              OptSpecifier OnOpt, OptSpecifier OffOpt,
298                              StringRef FeatureName) {
299   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
300     if (A->getOption().matches(OnOpt))
301       Features.push_back(Args.MakeArgString("+" + FeatureName));
302     else
303       Features.push_back(Args.MakeArgString("-" + FeatureName));
304   }
305 }
306 
307 /// Get the (LLVM) name of the AMDGPU gpu we are targeting.
308 static std::string getAMDGPUTargetGPU(const llvm::Triple &T,
309                                       const ArgList &Args) {
310   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
311     auto GPUName = getProcessorFromTargetID(T, A->getValue());
312     return llvm::StringSwitch<std::string>(GPUName)
313         .Cases("rv630", "rv635", "r600")
314         .Cases("rv610", "rv620", "rs780", "rs880")
315         .Case("rv740", "rv770")
316         .Case("palm", "cedar")
317         .Cases("sumo", "sumo2", "sumo")
318         .Case("hemlock", "cypress")
319         .Case("aruba", "cayman")
320         .Default(GPUName.str());
321   }
322   return "";
323 }
324 
325 static std::string getLanaiTargetCPU(const ArgList &Args) {
326   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
327     return A->getValue();
328   }
329   return "";
330 }
331 
332 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
333 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
334   // If we have -mcpu=, use that.
335   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
336     StringRef CPU = A->getValue();
337 
338 #ifdef __wasm__
339     // Handle "native" by examining the host. "native" isn't meaningful when
340     // cross compiling, so only support this when the host is also WebAssembly.
341     if (CPU == "native")
342       return llvm::sys::getHostCPUName();
343 #endif
344 
345     return CPU;
346   }
347 
348   return "generic";
349 }
350 
351 std::string tools::getCPUName(const Driver &D, const ArgList &Args,
352                               const llvm::Triple &T, bool FromAs) {
353   Arg *A;
354 
355   switch (T.getArch()) {
356   default:
357     return "";
358 
359   case llvm::Triple::aarch64:
360   case llvm::Triple::aarch64_32:
361   case llvm::Triple::aarch64_be:
362     return aarch64::getAArch64TargetCPU(Args, T, A);
363 
364   case llvm::Triple::arm:
365   case llvm::Triple::armeb:
366   case llvm::Triple::thumb:
367   case llvm::Triple::thumbeb: {
368     StringRef MArch, MCPU;
369     arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
370     return arm::getARMTargetCPU(MCPU, MArch, T);
371   }
372 
373   case llvm::Triple::avr:
374     if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
375       return A->getValue();
376     return "";
377 
378   case llvm::Triple::m68k:
379     return m68k::getM68kTargetCPU(Args);
380 
381   case llvm::Triple::mips:
382   case llvm::Triple::mipsel:
383   case llvm::Triple::mips64:
384   case llvm::Triple::mips64el: {
385     StringRef CPUName;
386     StringRef ABIName;
387     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
388     return std::string(CPUName);
389   }
390 
391   case llvm::Triple::nvptx:
392   case llvm::Triple::nvptx64:
393     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
394       return A->getValue();
395     return "";
396 
397   case llvm::Triple::ppc:
398   case llvm::Triple::ppcle:
399   case llvm::Triple::ppc64:
400   case llvm::Triple::ppc64le: {
401     std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
402     // LLVM may default to generating code for the native CPU,
403     // but, like gcc, we default to a more generic option for
404     // each architecture. (except on AIX)
405     if (!TargetCPUName.empty())
406       return TargetCPUName;
407 
408     if (T.isOSAIX())
409       TargetCPUName = "pwr7";
410     else if (T.getArch() == llvm::Triple::ppc64le)
411       TargetCPUName = "ppc64le";
412     else if (T.getArch() == llvm::Triple::ppc64)
413       TargetCPUName = "ppc64";
414     else
415       TargetCPUName = "ppc";
416 
417     return TargetCPUName;
418   }
419   case llvm::Triple::csky:
420     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
421       return A->getValue();
422     else if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
423       return A->getValue();
424     else
425       return "ck810";
426   case llvm::Triple::riscv32:
427   case llvm::Triple::riscv64:
428     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
429       return A->getValue();
430     return "";
431 
432   case llvm::Triple::bpfel:
433   case llvm::Triple::bpfeb:
434   case llvm::Triple::sparc:
435   case llvm::Triple::sparcel:
436   case llvm::Triple::sparcv9:
437     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
438       return A->getValue();
439     if (T.getArch() == llvm::Triple::sparc && T.isOSSolaris())
440       return "v9";
441     return "";
442 
443   case llvm::Triple::x86:
444   case llvm::Triple::x86_64:
445     return x86::getX86TargetCPU(D, Args, T);
446 
447   case llvm::Triple::hexagon:
448     return "hexagon" +
449            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
450 
451   case llvm::Triple::lanai:
452     return getLanaiTargetCPU(Args);
453 
454   case llvm::Triple::systemz:
455     return systemz::getSystemZTargetCPU(Args);
456 
457   case llvm::Triple::r600:
458   case llvm::Triple::amdgcn:
459     return getAMDGPUTargetGPU(T, Args);
460 
461   case llvm::Triple::wasm32:
462   case llvm::Triple::wasm64:
463     return std::string(getWebAssemblyTargetCPU(Args));
464   }
465 }
466 
467 llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
468   Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
469   if (!LtoJobsArg)
470     return {};
471   if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue()))
472     D.Diag(diag::err_drv_invalid_int_value)
473         << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
474   return LtoJobsArg->getValue();
475 }
476 
477 // CloudABI and PS4/PS5 use -ffunction-sections and -fdata-sections by default.
478 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
479   return Triple.getOS() == llvm::Triple::CloudABI || Triple.isPS();
480 }
481 
482 void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
483                           ArgStringList &CmdArgs, const InputInfo &Output,
484                           const InputInfo &Input, bool IsThinLTO) {
485   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
486   const Driver &D = ToolChain.getDriver();
487   if (llvm::sys::path::filename(Linker) != "ld.lld" &&
488       llvm::sys::path::stem(Linker) != "ld.lld") {
489     // Tell the linker to load the plugin. This has to come before
490     // AddLinkerInputs as gold requires -plugin to come before any -plugin-opt
491     // that -Wl might forward.
492     CmdArgs.push_back("-plugin");
493 
494 #if defined(_WIN32)
495     const char *Suffix = ".dll";
496 #elif defined(__APPLE__)
497     const char *Suffix = ".dylib";
498 #else
499     const char *Suffix = ".so";
500 #endif
501 
502     SmallString<1024> Plugin;
503     llvm::sys::path::native(
504         Twine(D.Dir) + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" + Suffix,
505         Plugin);
506     CmdArgs.push_back(Args.MakeArgString(Plugin));
507   }
508 
509   // Try to pass driver level flags relevant to LTO code generation down to
510   // the plugin.
511 
512   // Handle flags for selecting CPU variants.
513   std::string CPU = getCPUName(D, Args, ToolChain.getTriple());
514   if (!CPU.empty())
515     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
516 
517   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
518     // The optimization level matches
519     // CompilerInvocation.cpp:getOptimizationLevel().
520     StringRef OOpt;
521     if (A->getOption().matches(options::OPT_O4) ||
522         A->getOption().matches(options::OPT_Ofast))
523       OOpt = "3";
524     else if (A->getOption().matches(options::OPT_O)) {
525       OOpt = A->getValue();
526       if (OOpt == "g")
527         OOpt = "1";
528       else if (OOpt == "s" || OOpt == "z")
529         OOpt = "2";
530     } else if (A->getOption().matches(options::OPT_O0))
531       OOpt = "0";
532     if (!OOpt.empty())
533       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
534   }
535 
536   if (Args.hasArg(options::OPT_gsplit_dwarf)) {
537     CmdArgs.push_back(
538         Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
539             Output.getFilename() + "_dwo"));
540   }
541 
542   if (IsThinLTO)
543     CmdArgs.push_back("-plugin-opt=thinlto");
544 
545   StringRef Parallelism = getLTOParallelism(Args, D);
546   if (!Parallelism.empty())
547     CmdArgs.push_back(
548         Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
549 
550   if (!CLANG_ENABLE_OPAQUE_POINTERS_INTERNAL)
551     CmdArgs.push_back(Args.MakeArgString("-plugin-opt=no-opaque-pointers"));
552 
553   // If an explicit debugger tuning argument appeared, pass it along.
554   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
555                                options::OPT_ggdbN_Group)) {
556     if (A->getOption().matches(options::OPT_glldb))
557       CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
558     else if (A->getOption().matches(options::OPT_gsce))
559       CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
560     else if (A->getOption().matches(options::OPT_gdbx))
561       CmdArgs.push_back("-plugin-opt=-debugger-tune=dbx");
562     else
563       CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
564   }
565 
566   bool UseSeparateSections =
567       isUseSeparateSections(ToolChain.getEffectiveTriple());
568 
569   if (Args.hasFlag(options::OPT_ffunction_sections,
570                    options::OPT_fno_function_sections, UseSeparateSections)) {
571     CmdArgs.push_back("-plugin-opt=-function-sections");
572   }
573 
574   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
575                    UseSeparateSections)) {
576     CmdArgs.push_back("-plugin-opt=-data-sections");
577   }
578 
579   // Pass an option to enable split machine functions.
580   if (auto *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
581                                 options::OPT_fno_split_machine_functions)) {
582     if (A->getOption().matches(options::OPT_fsplit_machine_functions))
583       CmdArgs.push_back("-plugin-opt=-split-machine-functions");
584   }
585 
586   if (Arg *A = getLastProfileSampleUseArg(Args)) {
587     StringRef FName = A->getValue();
588     if (!llvm::sys::fs::exists(FName))
589       D.Diag(diag::err_drv_no_such_file) << FName;
590     else
591       CmdArgs.push_back(
592           Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
593   }
594 
595   auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
596                                            options::OPT_fcs_profile_generate_EQ,
597                                            options::OPT_fno_profile_generate);
598   if (CSPGOGenerateArg &&
599       CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
600     CSPGOGenerateArg = nullptr;
601 
602   auto *ProfileUseArg = getLastProfileUseArg(Args);
603 
604   if (CSPGOGenerateArg) {
605     CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate"));
606     if (CSPGOGenerateArg->getOption().matches(
607             options::OPT_fcs_profile_generate_EQ)) {
608       SmallString<128> Path(CSPGOGenerateArg->getValue());
609       llvm::sys::path::append(Path, "default_%m.profraw");
610       CmdArgs.push_back(
611           Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path));
612     } else
613       CmdArgs.push_back(
614           Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw"));
615   } else if (ProfileUseArg) {
616     SmallString<128> Path(
617         ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
618     if (Path.empty() || llvm::sys::fs::is_directory(Path))
619       llvm::sys::path::append(Path, "default.profdata");
620     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") +
621                                          Path));
622   }
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::addOpenMPRuntimeSpecificRPath(const ToolChain &TC,
649                                           const ArgList &Args,
650                                           ArgStringList &CmdArgs) {
651 
652   if (Args.hasFlag(options::OPT_fopenmp_implicit_rpath,
653                    options::OPT_fno_openmp_implicit_rpath, true)) {
654     // Default to clang lib / lib64 folder, i.e. the same location as device
655     // runtime
656     SmallString<256> DefaultLibPath =
657         llvm::sys::path::parent_path(TC.getDriver().Dir);
658     llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
659     CmdArgs.push_back("-rpath");
660     CmdArgs.push_back(Args.MakeArgString(DefaultLibPath));
661   }
662 }
663 
664 void tools::addOpenMPRuntimeLibraryPath(const ToolChain &TC,
665                                         const ArgList &Args,
666                                         ArgStringList &CmdArgs) {
667   // Default to clang lib / lib64 folder, i.e. the same location as device
668   // runtime.
669   SmallString<256> DefaultLibPath =
670       llvm::sys::path::parent_path(TC.getDriver().Dir);
671   llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
672   CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
673 }
674 
675 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
676                                  ArgStringList &CmdArgs) {
677   // Enable -frtlib-add-rpath by default for the case of VE.
678   const bool IsVE = TC.getTriple().isVE();
679   bool DefaultValue = IsVE;
680   if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
681                     options::OPT_fno_rtlib_add_rpath, DefaultValue))
682     return;
683 
684   std::string CandidateRPath = TC.getArchSpecificLibPath();
685   if (TC.getVFS().exists(CandidateRPath)) {
686     CmdArgs.push_back("-rpath");
687     CmdArgs.push_back(Args.MakeArgString(CandidateRPath));
688   }
689 }
690 
691 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
692                              const ArgList &Args, bool ForceStaticHostRuntime,
693                              bool IsOffloadingHost, bool GompNeedsRT) {
694   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
695                     options::OPT_fno_openmp, false))
696     return false;
697 
698   Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
699 
700   if (RTKind == Driver::OMPRT_Unknown)
701     // Already diagnosed.
702     return false;
703 
704   if (ForceStaticHostRuntime)
705     CmdArgs.push_back("-Bstatic");
706 
707   switch (RTKind) {
708   case Driver::OMPRT_OMP:
709     CmdArgs.push_back("-lomp");
710     break;
711   case Driver::OMPRT_GOMP:
712     CmdArgs.push_back("-lgomp");
713     break;
714   case Driver::OMPRT_IOMP5:
715     CmdArgs.push_back("-liomp5");
716     break;
717   case Driver::OMPRT_Unknown:
718     break;
719   }
720 
721   if (ForceStaticHostRuntime)
722     CmdArgs.push_back("-Bdynamic");
723 
724   if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
725       CmdArgs.push_back("-lrt");
726 
727   if (IsOffloadingHost)
728     CmdArgs.push_back("-lomptarget");
729 
730   if (IsOffloadingHost && TC.getDriver().isUsingLTO(/* IsOffload */ true) &&
731       !Args.hasArg(options::OPT_nogpulib))
732     CmdArgs.push_back("-lomptarget.devicertl");
733 
734   addArchSpecificRPath(TC, Args, CmdArgs);
735 
736   if (RTKind == Driver::OMPRT_OMP)
737     addOpenMPRuntimeSpecificRPath(TC, Args, CmdArgs);
738   addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs);
739 
740   return true;
741 }
742 
743 void tools::addFortranRuntimeLibs(const ToolChain &TC,
744                                   llvm::opt::ArgStringList &CmdArgs) {
745   if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
746     CmdArgs.push_back("Fortran_main.lib");
747     CmdArgs.push_back("FortranRuntime.lib");
748     CmdArgs.push_back("FortranDecimal.lib");
749   } else {
750     CmdArgs.push_back("-lFortran_main");
751     CmdArgs.push_back("-lFortranRuntime");
752     CmdArgs.push_back("-lFortranDecimal");
753   }
754 }
755 
756 void tools::addFortranRuntimeLibraryPath(const ToolChain &TC,
757                                          const llvm::opt::ArgList &Args,
758                                          ArgStringList &CmdArgs) {
759   // NOTE: Generating executables by Flang is considered an "experimental"
760   // feature and hence this is guarded with a command line option.
761   // TODO: Make this work unconditionally once Flang is mature enough.
762   if (!Args.hasArg(options::OPT_flang_experimental_exec))
763     return;
764 
765   // Default to the <driver-path>/../lib directory. This works fine on the
766   // platforms that we have tested so far. We will probably have to re-fine
767   // this in the future. In particular, on some platforms, we may need to use
768   // lib64 instead of lib.
769   SmallString<256> DefaultLibPath =
770       llvm::sys::path::parent_path(TC.getDriver().Dir);
771   llvm::sys::path::append(DefaultLibPath, "lib");
772   if (TC.getTriple().isKnownWindowsMSVCEnvironment())
773     CmdArgs.push_back(Args.MakeArgString("-libpath:" + DefaultLibPath));
774   else
775     CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
776 }
777 
778 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
779                                 ArgStringList &CmdArgs, StringRef Sanitizer,
780                                 bool IsShared, bool IsWhole) {
781   // Wrap any static runtimes that must be forced into executable in
782   // whole-archive.
783   if (IsWhole) CmdArgs.push_back("--whole-archive");
784   CmdArgs.push_back(TC.getCompilerRTArgString(
785       Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
786   if (IsWhole) CmdArgs.push_back("--no-whole-archive");
787 
788   if (IsShared) {
789     addArchSpecificRPath(TC, Args, CmdArgs);
790   }
791 }
792 
793 // Tries to use a file with the list of dynamic symbols that need to be exported
794 // from the runtime library. Returns true if the file was found.
795 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
796                                     ArgStringList &CmdArgs,
797                                     StringRef Sanitizer) {
798   // Solaris ld defaults to --export-dynamic behaviour but doesn't support
799   // the option, so don't try to pass it.
800   if (TC.getTriple().getOS() == llvm::Triple::Solaris)
801     return true;
802   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
803   if (llvm::sys::fs::exists(SanRT + ".syms")) {
804     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
805     return true;
806   }
807   return false;
808 }
809 
810 const char *tools::getAsNeededOption(const ToolChain &TC, bool as_needed) {
811   assert(!TC.getTriple().isOSAIX() &&
812          "AIX linker does not support any form of --as-needed option yet.");
813 
814   // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
815   // for the native forms -z ignore/-z record, they are missing in Illumos,
816   // so always use the native form.
817   if (TC.getTriple().isOSSolaris())
818     return as_needed ? "-zignore" : "-zrecord";
819   else
820     return as_needed ? "--as-needed" : "--no-as-needed";
821 }
822 
823 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
824                                      ArgStringList &CmdArgs) {
825   // Force linking against the system libraries sanitizers depends on
826   // (see PR15823 why this is necessary).
827   CmdArgs.push_back(getAsNeededOption(TC, false));
828   // There's no libpthread or librt on RTEMS & Android.
829   if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
830       !TC.getTriple().isAndroid()) {
831     CmdArgs.push_back("-lpthread");
832     if (!TC.getTriple().isOSOpenBSD())
833       CmdArgs.push_back("-lrt");
834   }
835   CmdArgs.push_back("-lm");
836   // There's no libdl on all OSes.
837   if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() &&
838       !TC.getTriple().isOSOpenBSD() &&
839       TC.getTriple().getOS() != llvm::Triple::RTEMS)
840     CmdArgs.push_back("-ldl");
841   // Required for backtrace on some OSes
842   if (TC.getTriple().isOSFreeBSD() ||
843       TC.getTriple().isOSNetBSD() ||
844       TC.getTriple().isOSOpenBSD())
845     CmdArgs.push_back("-lexecinfo");
846   // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl
847   // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv
848   // requirement.
849   if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() &&
850       !TC.getTriple().isMusl())
851     CmdArgs.push_back("-lresolv");
852 }
853 
854 static void
855 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
856                          SmallVectorImpl<StringRef> &SharedRuntimes,
857                          SmallVectorImpl<StringRef> &StaticRuntimes,
858                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
859                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
860                          SmallVectorImpl<StringRef> &RequiredSymbols) {
861   const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
862   // Collect shared runtimes.
863   if (SanArgs.needsSharedRt()) {
864     if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
865       SharedRuntimes.push_back("asan");
866       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
867         HelperStaticRuntimes.push_back("asan-preinit");
868     }
869     if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) {
870       SharedRuntimes.push_back("memprof");
871       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
872         HelperStaticRuntimes.push_back("memprof-preinit");
873     }
874     if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
875       if (SanArgs.requiresMinimalRuntime())
876         SharedRuntimes.push_back("ubsan_minimal");
877       else
878         SharedRuntimes.push_back("ubsan_standalone");
879     }
880     if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
881       if (SanArgs.requiresMinimalRuntime())
882         SharedRuntimes.push_back("scudo_minimal");
883       else
884         SharedRuntimes.push_back("scudo");
885     }
886     if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes())
887       SharedRuntimes.push_back("tsan");
888     if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
889       if (SanArgs.needsHwasanAliasesRt())
890         SharedRuntimes.push_back("hwasan_aliases");
891       else
892         SharedRuntimes.push_back("hwasan");
893       if (!Args.hasArg(options::OPT_shared))
894         HelperStaticRuntimes.push_back("hwasan-preinit");
895     }
896   }
897 
898   // The stats_client library is also statically linked into DSOs.
899   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
900     StaticRuntimes.push_back("stats_client");
901 
902   // Always link the static runtime regardless of DSO or executable.
903   if (SanArgs.needsAsanRt())
904     HelperStaticRuntimes.push_back("asan_static");
905 
906   // Collect static runtimes.
907   if (Args.hasArg(options::OPT_shared)) {
908     // Don't link static runtimes into DSOs.
909     return;
910   }
911 
912   // Each static runtime that has a DSO counterpart above is excluded below,
913   // but runtimes that exist only as static are not affected by needsSharedRt.
914 
915   if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
916     StaticRuntimes.push_back("asan");
917     if (SanArgs.linkCXXRuntimes())
918       StaticRuntimes.push_back("asan_cxx");
919   }
920 
921   if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt() &&
922       SanArgs.linkRuntimes()) {
923     StaticRuntimes.push_back("memprof");
924     if (SanArgs.linkCXXRuntimes())
925       StaticRuntimes.push_back("memprof_cxx");
926   }
927 
928   if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
929     if (SanArgs.needsHwasanAliasesRt()) {
930       StaticRuntimes.push_back("hwasan_aliases");
931       if (SanArgs.linkCXXRuntimes())
932         StaticRuntimes.push_back("hwasan_aliases_cxx");
933     } else {
934       StaticRuntimes.push_back("hwasan");
935       if (SanArgs.linkCXXRuntimes())
936         StaticRuntimes.push_back("hwasan_cxx");
937     }
938   }
939   if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes())
940     StaticRuntimes.push_back("dfsan");
941   if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes())
942     StaticRuntimes.push_back("lsan");
943   if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) {
944     StaticRuntimes.push_back("msan");
945     if (SanArgs.linkCXXRuntimes())
946       StaticRuntimes.push_back("msan_cxx");
947   }
948   if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt() &&
949       SanArgs.linkRuntimes()) {
950     StaticRuntimes.push_back("tsan");
951     if (SanArgs.linkCXXRuntimes())
952       StaticRuntimes.push_back("tsan_cxx");
953   }
954   if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
955     if (SanArgs.requiresMinimalRuntime()) {
956       StaticRuntimes.push_back("ubsan_minimal");
957     } else {
958       StaticRuntimes.push_back("ubsan_standalone");
959       if (SanArgs.linkCXXRuntimes())
960         StaticRuntimes.push_back("ubsan_standalone_cxx");
961     }
962   }
963   if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) {
964     NonWholeStaticRuntimes.push_back("safestack");
965     RequiredSymbols.push_back("__safestack_init");
966   }
967   if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) {
968     if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
969       StaticRuntimes.push_back("cfi");
970     if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) {
971       StaticRuntimes.push_back("cfi_diag");
972       if (SanArgs.linkCXXRuntimes())
973         StaticRuntimes.push_back("ubsan_standalone_cxx");
974     }
975   }
976   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) {
977     NonWholeStaticRuntimes.push_back("stats");
978     RequiredSymbols.push_back("__sanitizer_stats_register");
979   }
980   if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
981     if (SanArgs.requiresMinimalRuntime()) {
982       StaticRuntimes.push_back("scudo_minimal");
983       if (SanArgs.linkCXXRuntimes())
984         StaticRuntimes.push_back("scudo_cxx_minimal");
985     } else {
986       StaticRuntimes.push_back("scudo");
987       if (SanArgs.linkCXXRuntimes())
988         StaticRuntimes.push_back("scudo_cxx");
989     }
990   }
991 }
992 
993 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
994 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
995 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
996                                  ArgStringList &CmdArgs) {
997   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
998       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
999   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
1000                            NonWholeStaticRuntimes, HelperStaticRuntimes,
1001                            RequiredSymbols);
1002 
1003   const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
1004   // Inject libfuzzer dependencies.
1005   if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
1006       !Args.hasArg(options::OPT_shared)) {
1007 
1008     addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
1009     if (SanArgs.needsFuzzerInterceptors())
1010       addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
1011                           true);
1012     if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
1013       bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
1014                                  !Args.hasArg(options::OPT_static);
1015       if (OnlyLibstdcxxStatic)
1016         CmdArgs.push_back("-Bstatic");
1017       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
1018       if (OnlyLibstdcxxStatic)
1019         CmdArgs.push_back("-Bdynamic");
1020     }
1021   }
1022 
1023   for (auto RT : SharedRuntimes)
1024     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
1025   for (auto RT : HelperStaticRuntimes)
1026     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1027   bool AddExportDynamic = false;
1028   for (auto RT : StaticRuntimes) {
1029     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1030     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1031   }
1032   for (auto RT : NonWholeStaticRuntimes) {
1033     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
1034     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1035   }
1036   for (auto S : RequiredSymbols) {
1037     CmdArgs.push_back("-u");
1038     CmdArgs.push_back(Args.MakeArgString(S));
1039   }
1040   // If there is a static runtime with no dynamic list, force all the symbols
1041   // to be dynamic to be sure we export sanitizer interface functions.
1042   if (AddExportDynamic)
1043     CmdArgs.push_back("--export-dynamic");
1044 
1045   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
1046     CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
1047 
1048   if (SanArgs.hasMemTag()) {
1049     if (!TC.getTriple().isAndroid()) {
1050       TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1051           << "-fsanitize=memtag*" << TC.getTriple().str();
1052     }
1053     CmdArgs.push_back(
1054         Args.MakeArgString("--android-memtag-mode=" + SanArgs.getMemtagMode()));
1055     if (SanArgs.hasMemtagHeap())
1056       CmdArgs.push_back("--android-memtag-heap");
1057     if (SanArgs.hasMemtagStack())
1058       CmdArgs.push_back("--android-memtag-stack");
1059   }
1060 
1061   return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
1062 }
1063 
1064 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
1065   if (Args.hasArg(options::OPT_shared))
1066     return false;
1067 
1068   if (TC.getXRayArgs().needsXRayRt()) {
1069     CmdArgs.push_back("-whole-archive");
1070     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
1071     for (const auto &Mode : TC.getXRayArgs().modeList())
1072       CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
1073     CmdArgs.push_back("-no-whole-archive");
1074     return true;
1075   }
1076 
1077   return false;
1078 }
1079 
1080 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
1081   CmdArgs.push_back(getAsNeededOption(TC, false));
1082   CmdArgs.push_back("-lpthread");
1083   if (!TC.getTriple().isOSOpenBSD())
1084     CmdArgs.push_back("-lrt");
1085   CmdArgs.push_back("-lm");
1086 
1087   if (!TC.getTriple().isOSFreeBSD() &&
1088       !TC.getTriple().isOSNetBSD() &&
1089       !TC.getTriple().isOSOpenBSD())
1090     CmdArgs.push_back("-ldl");
1091 }
1092 
1093 bool tools::areOptimizationsEnabled(const ArgList &Args) {
1094   // Find the last -O arg and see if it is non-zero.
1095   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1096     return !A->getOption().matches(options::OPT_O0);
1097   // Defaults to -O0.
1098   return false;
1099 }
1100 
1101 const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
1102                                   const InputInfo &Input,
1103                                   const InputInfo &Output) {
1104   auto AddPostfix = [JA](auto &F) {
1105     if (JA.getOffloadingDeviceKind() == Action::OFK_HIP)
1106       F += (Twine("_") + JA.getOffloadingArch()).str();
1107     F += ".dwo";
1108   };
1109   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
1110     if (StringRef(A->getValue()) == "single")
1111       return Args.MakeArgString(Output.getFilename());
1112 
1113   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
1114   if (FinalOutput && Args.hasArg(options::OPT_c)) {
1115     SmallString<128> T(FinalOutput->getValue());
1116     llvm::sys::path::remove_filename(T);
1117     llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue()));
1118     AddPostfix(T);
1119     return Args.MakeArgString(T);
1120   } else {
1121     // Use the compilation dir.
1122     Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
1123                              options::OPT_fdebug_compilation_dir_EQ);
1124     SmallString<128> T(A ? A->getValue() : "");
1125     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
1126     AddPostfix(F);
1127     T += F;
1128     return Args.MakeArgString(T);
1129   }
1130 }
1131 
1132 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
1133                            const JobAction &JA, const ArgList &Args,
1134                            const InputInfo &Output, const char *OutFile) {
1135   ArgStringList ExtractArgs;
1136   ExtractArgs.push_back("--extract-dwo");
1137 
1138   ArgStringList StripArgs;
1139   StripArgs.push_back("--strip-dwo");
1140 
1141   // Grabbing the output of the earlier compile step.
1142   StripArgs.push_back(Output.getFilename());
1143   ExtractArgs.push_back(Output.getFilename());
1144   ExtractArgs.push_back(OutFile);
1145 
1146   const char *Exec =
1147       Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
1148   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1149 
1150   // First extract the dwo sections.
1151   C.addCommand(std::make_unique<Command>(JA, T,
1152                                          ResponseFileSupport::AtFileCurCP(),
1153                                          Exec, ExtractArgs, II, Output));
1154 
1155   // Then remove them from the original .o file.
1156   C.addCommand(std::make_unique<Command>(
1157       JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
1158 }
1159 
1160 // Claim options we don't want to warn if they are unused. We do this for
1161 // options that build systems might add but are unused when assembling or only
1162 // running the preprocessor for example.
1163 void tools::claimNoWarnArgs(const ArgList &Args) {
1164   // Don't warn about unused -f(no-)?lto.  This can happen when we're
1165   // preprocessing, precompiling or assembling.
1166   Args.ClaimAllArgs(options::OPT_flto_EQ);
1167   Args.ClaimAllArgs(options::OPT_flto);
1168   Args.ClaimAllArgs(options::OPT_fno_lto);
1169 }
1170 
1171 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
1172   auto *ProfileUseArg = Args.getLastArg(
1173       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
1174       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
1175       options::OPT_fno_profile_instr_use);
1176 
1177   if (ProfileUseArg &&
1178       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
1179     ProfileUseArg = nullptr;
1180 
1181   return ProfileUseArg;
1182 }
1183 
1184 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
1185   auto *ProfileSampleUseArg = Args.getLastArg(
1186       options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
1187       options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
1188       options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
1189 
1190   if (ProfileSampleUseArg &&
1191       (ProfileSampleUseArg->getOption().matches(
1192            options::OPT_fno_profile_sample_use) ||
1193        ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
1194     return nullptr;
1195 
1196   return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
1197                          options::OPT_fauto_profile_EQ);
1198 }
1199 
1200 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
1201 /// smooshes them together with platform defaults, to decide whether
1202 /// this compile should be using PIC mode or not. Returns a tuple of
1203 /// (RelocationModel, PICLevel, IsPIE).
1204 std::tuple<llvm::Reloc::Model, unsigned, bool>
1205 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
1206   const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
1207   const llvm::Triple &Triple = ToolChain.getTriple();
1208 
1209   bool PIE = ToolChain.isPIEDefault(Args);
1210   bool PIC = PIE || ToolChain.isPICDefault();
1211   // The Darwin/MachO default to use PIC does not apply when using -static.
1212   if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
1213     PIE = PIC = false;
1214   bool IsPICLevelTwo = PIC;
1215 
1216   bool KernelOrKext =
1217       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1218 
1219   // Android-specific defaults for PIC/PIE
1220   if (Triple.isAndroid()) {
1221     switch (Triple.getArch()) {
1222     case llvm::Triple::arm:
1223     case llvm::Triple::armeb:
1224     case llvm::Triple::thumb:
1225     case llvm::Triple::thumbeb:
1226     case llvm::Triple::aarch64:
1227     case llvm::Triple::mips:
1228     case llvm::Triple::mipsel:
1229     case llvm::Triple::mips64:
1230     case llvm::Triple::mips64el:
1231       PIC = true; // "-fpic"
1232       break;
1233 
1234     case llvm::Triple::x86:
1235     case llvm::Triple::x86_64:
1236       PIC = true; // "-fPIC"
1237       IsPICLevelTwo = true;
1238       break;
1239 
1240     default:
1241       break;
1242     }
1243   }
1244 
1245   // OpenBSD-specific defaults for PIE
1246   if (Triple.isOSOpenBSD()) {
1247     switch (ToolChain.getArch()) {
1248     case llvm::Triple::arm:
1249     case llvm::Triple::aarch64:
1250     case llvm::Triple::mips64:
1251     case llvm::Triple::mips64el:
1252     case llvm::Triple::x86:
1253     case llvm::Triple::x86_64:
1254       IsPICLevelTwo = false; // "-fpie"
1255       break;
1256 
1257     case llvm::Triple::ppc:
1258     case llvm::Triple::sparcv9:
1259       IsPICLevelTwo = true; // "-fPIE"
1260       break;
1261 
1262     default:
1263       break;
1264     }
1265   }
1266 
1267   // AMDGPU-specific defaults for PIC.
1268   if (Triple.getArch() == llvm::Triple::amdgcn)
1269     PIC = true;
1270 
1271   // The last argument relating to either PIC or PIE wins, and no
1272   // other argument is used. If the last argument is any flavor of the
1273   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1274   // option implicitly enables PIC at the same level.
1275   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1276                                     options::OPT_fpic, options::OPT_fno_pic,
1277                                     options::OPT_fPIE, options::OPT_fno_PIE,
1278                                     options::OPT_fpie, options::OPT_fno_pie);
1279   if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg &&
1280       LastPICArg == Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1281                                     options::OPT_fPIE, options::OPT_fpie)) {
1282     ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1283         << LastPICArg->getSpelling() << Triple.str();
1284     if (Triple.getArch() == llvm::Triple::x86_64)
1285       return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1286     return std::make_tuple(llvm::Reloc::Static, 0U, false);
1287   }
1288 
1289   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1290   // is forced, then neither PIC nor PIE flags will have no effect.
1291   if (!ToolChain.isPICDefaultForced()) {
1292     if (LastPICArg) {
1293       Option O = LastPICArg->getOption();
1294       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1295           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1296         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1297         PIC =
1298             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1299         IsPICLevelTwo =
1300             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1301       } else {
1302         PIE = PIC = false;
1303         if (EffectiveTriple.isPS()) {
1304           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1305           StringRef Model = ModelArg ? ModelArg->getValue() : "";
1306           if (Model != "kernel") {
1307             PIC = true;
1308             ToolChain.getDriver().Diag(diag::warn_drv_ps_force_pic)
1309                 << LastPICArg->getSpelling()
1310                 << (EffectiveTriple.isPS4() ? "PS4" : "PS5");
1311           }
1312         }
1313       }
1314     }
1315   }
1316 
1317   // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but
1318   // the PIC level would've been set to level 1, force it back to level 2 PIC
1319   // instead.
1320   if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS()))
1321     IsPICLevelTwo |= ToolChain.isPICDefault();
1322 
1323   // This kernel flags are a trump-card: they will disable PIC/PIE
1324   // generation, independent of the argument order.
1325   if (KernelOrKext &&
1326       ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1327        !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit()))
1328     PIC = PIE = false;
1329 
1330   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1331     // This is a very special mode. It trumps the other modes, almost no one
1332     // uses it, and it isn't even valid on any OS but Darwin.
1333     if (!Triple.isOSDarwin())
1334       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1335           << A->getSpelling() << Triple.str();
1336 
1337     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1338 
1339     // Only a forced PIC mode can cause the actual compile to have PIC defines
1340     // etc., no flags are sufficient. This behavior was selected to closely
1341     // match that of llvm-gcc and Apple GCC before that.
1342     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1343 
1344     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1345   }
1346 
1347   bool EmbeddedPISupported;
1348   switch (Triple.getArch()) {
1349     case llvm::Triple::arm:
1350     case llvm::Triple::armeb:
1351     case llvm::Triple::thumb:
1352     case llvm::Triple::thumbeb:
1353       EmbeddedPISupported = true;
1354       break;
1355     default:
1356       EmbeddedPISupported = false;
1357       break;
1358   }
1359 
1360   bool ROPI = false, RWPI = false;
1361   Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1362   if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1363     if (!EmbeddedPISupported)
1364       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1365           << LastROPIArg->getSpelling() << Triple.str();
1366     ROPI = true;
1367   }
1368   Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1369   if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1370     if (!EmbeddedPISupported)
1371       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1372           << LastRWPIArg->getSpelling() << Triple.str();
1373     RWPI = true;
1374   }
1375 
1376   // ROPI and RWPI are not compatible with PIC or PIE.
1377   if ((ROPI || RWPI) && (PIC || PIE))
1378     ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1379 
1380   if (Triple.isMIPS()) {
1381     StringRef CPUName;
1382     StringRef ABIName;
1383     mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1384     // When targeting the N64 ABI, PIC is the default, except in the case
1385     // when the -mno-abicalls option is used. In that case we exit
1386     // at next check regardless of PIC being set below.
1387     if (ABIName == "n64")
1388       PIC = true;
1389     // When targettng MIPS with -mno-abicalls, it's always static.
1390     if(Args.hasArg(options::OPT_mno_abicalls))
1391       return std::make_tuple(llvm::Reloc::Static, 0U, false);
1392     // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1393     // does not use PIC level 2 for historical reasons.
1394     IsPICLevelTwo = false;
1395   }
1396 
1397   if (PIC)
1398     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1399 
1400   llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1401   if (ROPI && RWPI)
1402     RelocM = llvm::Reloc::ROPI_RWPI;
1403   else if (ROPI)
1404     RelocM = llvm::Reloc::ROPI;
1405   else if (RWPI)
1406     RelocM = llvm::Reloc::RWPI;
1407 
1408   return std::make_tuple(RelocM, 0U, false);
1409 }
1410 
1411 // `-falign-functions` indicates that the functions should be aligned to a
1412 // 16-byte boundary.
1413 //
1414 // `-falign-functions=1` is the same as `-fno-align-functions`.
1415 //
1416 // The scalar `n` in `-falign-functions=n` must be an integral value between
1417 // [0, 65536].  If the value is not a power-of-two, it will be rounded up to
1418 // the nearest power-of-two.
1419 //
1420 // If we return `0`, the frontend will default to the backend's preferred
1421 // alignment.
1422 //
1423 // NOTE: icc only allows values between [0, 4096].  icc uses `-falign-functions`
1424 // to mean `-falign-functions=16`.  GCC defaults to the backend's preferred
1425 // alignment.  For unaligned functions, we default to the backend's preferred
1426 // alignment.
1427 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1428                                        const ArgList &Args) {
1429   const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1430                                  options::OPT_falign_functions_EQ,
1431                                  options::OPT_fno_align_functions);
1432   if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1433     return 0;
1434 
1435   if (A->getOption().matches(options::OPT_falign_functions))
1436     return 0;
1437 
1438   unsigned Value = 0;
1439   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1440     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1441         << A->getAsString(Args) << A->getValue();
1442   return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1443 }
1444 
1445 unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC,
1446                                          const ArgList &Args) {
1447   const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
1448 
1449   if (!A)
1450     return 0;
1451 
1452   unsigned Value = 0;
1453   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
1454       Value < 2)
1455     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1456         << A->getAsString(Args) << A->getValue();
1457   return Value;
1458 }
1459 
1460 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1461                              ArgStringList &CmdArgs) {
1462   llvm::Reloc::Model RelocationModel;
1463   unsigned PICLevel;
1464   bool IsPIE;
1465   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1466 
1467   if (RelocationModel != llvm::Reloc::Static)
1468     CmdArgs.push_back("-KPIC");
1469 }
1470 
1471 /// Determine whether Objective-C automated reference counting is
1472 /// enabled.
1473 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1474   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1475 }
1476 
1477 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
1478 
1479 static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
1480                                 const ArgList &Args) {
1481   if (Args.hasArg(options::OPT_static_libgcc) ||
1482       Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie) ||
1483       // The Android NDK only provides libunwind.a, not libunwind.so.
1484       TC.getTriple().isAndroid())
1485     return LibGccType::StaticLibGcc;
1486   if (Args.hasArg(options::OPT_shared_libgcc))
1487     return LibGccType::SharedLibGcc;
1488   return LibGccType::UnspecifiedLibGcc;
1489 }
1490 
1491 // Gcc adds libgcc arguments in various ways:
1492 //
1493 // gcc <none>:     -lgcc --as-needed -lgcc_s --no-as-needed
1494 // g++ <none>:                       -lgcc_s               -lgcc
1495 // gcc shared:                       -lgcc_s               -lgcc
1496 // g++ shared:                       -lgcc_s               -lgcc
1497 // gcc static:     -lgcc             -lgcc_eh
1498 // g++ static:     -lgcc             -lgcc_eh
1499 // gcc static-pie: -lgcc             -lgcc_eh
1500 // g++ static-pie: -lgcc             -lgcc_eh
1501 //
1502 // Also, certain targets need additional adjustments.
1503 
1504 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
1505                              ArgStringList &CmdArgs, const ArgList &Args) {
1506   ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
1507   // Targets that don't use unwind libraries.
1508   if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
1509       TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
1510       UNW == ToolChain::UNW_None)
1511     return;
1512 
1513   LibGccType LGT = getLibGccType(TC, D, Args);
1514   bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
1515                   (UNW == ToolChain::UNW_CompilerRT || !D.CCCIsCXX()) &&
1516                   !TC.getTriple().isAndroid() &&
1517                   !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX();
1518   if (AsNeeded)
1519     CmdArgs.push_back(getAsNeededOption(TC, true));
1520 
1521   switch (UNW) {
1522   case ToolChain::UNW_None:
1523     return;
1524   case ToolChain::UNW_Libgcc: {
1525     if (LGT == LibGccType::StaticLibGcc)
1526       CmdArgs.push_back("-lgcc_eh");
1527     else
1528       CmdArgs.push_back("-lgcc_s");
1529     break;
1530   }
1531   case ToolChain::UNW_CompilerRT:
1532     if (TC.getTriple().isOSAIX()) {
1533       // AIX only has libunwind as a shared library. So do not pass
1534       // anything in if -static is specified.
1535       if (LGT != LibGccType::StaticLibGcc)
1536         CmdArgs.push_back("-lunwind");
1537     } else if (LGT == LibGccType::StaticLibGcc) {
1538       CmdArgs.push_back("-l:libunwind.a");
1539     } else if (LGT == LibGccType::SharedLibGcc) {
1540       if (TC.getTriple().isOSCygMing())
1541         CmdArgs.push_back("-l:libunwind.dll.a");
1542       else
1543         CmdArgs.push_back("-l:libunwind.so");
1544     } else {
1545       // Let the linker choose between libunwind.so and libunwind.a
1546       // depending on what's available, and depending on the -static flag
1547       CmdArgs.push_back("-lunwind");
1548     }
1549     break;
1550   }
1551 
1552   if (AsNeeded)
1553     CmdArgs.push_back(getAsNeededOption(TC, false));
1554 }
1555 
1556 static void AddLibgcc(const ToolChain &TC, const Driver &D,
1557                       ArgStringList &CmdArgs, const ArgList &Args) {
1558   LibGccType LGT = getLibGccType(TC, D, Args);
1559   if (LGT == LibGccType::StaticLibGcc ||
1560       (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX()))
1561     CmdArgs.push_back("-lgcc");
1562   AddUnwindLibrary(TC, D, CmdArgs, Args);
1563   if (LGT == LibGccType::SharedLibGcc ||
1564       (LGT == LibGccType::UnspecifiedLibGcc && D.CCCIsCXX()))
1565     CmdArgs.push_back("-lgcc");
1566 }
1567 
1568 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1569                            ArgStringList &CmdArgs, const ArgList &Args) {
1570   // Make use of compiler-rt if --rtlib option is used
1571   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1572 
1573   switch (RLT) {
1574   case ToolChain::RLT_CompilerRT:
1575     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1576     AddUnwindLibrary(TC, D, CmdArgs, Args);
1577     break;
1578   case ToolChain::RLT_Libgcc:
1579     // Make sure libgcc is not used under MSVC environment by default
1580     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1581       // Issue error diagnostic if libgcc is explicitly specified
1582       // through command line as --rtlib option argument.
1583       if (Args.hasArg(options::OPT_rtlib_EQ)) {
1584         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1585             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1586       }
1587     } else
1588       AddLibgcc(TC, D, CmdArgs, Args);
1589     break;
1590   }
1591 
1592   // On Android, the unwinder uses dl_iterate_phdr (or one of
1593   // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
1594   // statically-linked executables, these functions come from libc.a instead.
1595   if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) &&
1596       !Args.hasArg(options::OPT_static_pie))
1597     CmdArgs.push_back("-ldl");
1598 }
1599 
1600 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1601                                          const InputInfo &Output,
1602                                          const InputInfo &Input,
1603                                          const Driver &D) {
1604   const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1605   if (!A)
1606     return {};
1607 
1608   StringRef SaveStats = A->getValue();
1609   SmallString<128> StatsFile;
1610   if (SaveStats == "obj" && Output.isFilename()) {
1611     StatsFile.assign(Output.getFilename());
1612     llvm::sys::path::remove_filename(StatsFile);
1613   } else if (SaveStats != "cwd") {
1614     D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1615     return {};
1616   }
1617 
1618   StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1619   llvm::sys::path::append(StatsFile, BaseName);
1620   llvm::sys::path::replace_extension(StatsFile, "stats");
1621   return StatsFile;
1622 }
1623 
1624 void tools::addMultilibFlag(bool Enabled, const char *const Flag,
1625                             Multilib::flags_list &Flags) {
1626   Flags.push_back(std::string(Enabled ? "+" : "-") + Flag);
1627 }
1628 
1629 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
1630                                   ArgStringList &CmdArgs, bool IsLTO) {
1631   auto addArg = [&, IsLTO](const Twine &Arg) {
1632     if (IsLTO) {
1633       CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
1634     } else {
1635       CmdArgs.push_back("-mllvm");
1636       CmdArgs.push_back(Args.MakeArgString(Arg));
1637     }
1638   };
1639 
1640   if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
1641     addArg(Twine("-x86-branches-within-32B-boundaries"));
1642   }
1643   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
1644     StringRef Value = A->getValue();
1645     unsigned Boundary;
1646     if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
1647         !llvm::isPowerOf2_64(Boundary)) {
1648       D.Diag(diag::err_drv_invalid_argument_to_option)
1649           << Value << A->getOption().getName();
1650     } else {
1651       addArg("-x86-align-branch-boundary=" + Twine(Boundary));
1652     }
1653   }
1654   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
1655     std::string AlignBranch;
1656     for (StringRef T : A->getValues()) {
1657       if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
1658           T != "ret" && T != "indirect")
1659         D.Diag(diag::err_drv_invalid_malign_branch_EQ)
1660             << T << "fused, jcc, jmp, call, ret, indirect";
1661       if (!AlignBranch.empty())
1662         AlignBranch += '+';
1663       AlignBranch += T;
1664     }
1665     addArg("-x86-align-branch=" + Twine(AlignBranch));
1666   }
1667   if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
1668     StringRef Value = A->getValue();
1669     unsigned PrefixSize;
1670     if (Value.getAsInteger(10, PrefixSize)) {
1671       D.Diag(diag::err_drv_invalid_argument_to_option)
1672           << Value << A->getOption().getName();
1673     } else {
1674       addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
1675     }
1676   }
1677 }
1678 
1679 /// SDLSearch: Search for Static Device Library
1680 /// The search for SDL bitcode files is consistent with how static host
1681 /// libraries are discovered. That is, the -l option triggers a search for
1682 /// files in a set of directories called the LINKPATH. The host library search
1683 /// procedure looks for a specific filename in the LINKPATH.  The filename for
1684 /// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an
1685 /// ordered-set of filenames that are searched. We call this ordered-set of
1686 /// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific,
1687 /// architecture specific, or generic across all architectures, a naming
1688 /// convention and search order is used where the file name embeds the
1689 /// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type
1690 /// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of
1691 /// device-independent SDLs. To reduce congestion in host library directories,
1692 /// the search first looks for files in the “libdevice” subdirectory. SDLs that
1693 /// are bc files begin with the prefix “lib”.
1694 ///
1695 /// Machine-code SDLs can also be managed as an archive (*.a file). The
1696 /// convention has been to use the prefix “lib”. To avoid confusion with host
1697 /// archive libraries, we use prefix "libbc-" for the bitcode SDL archives.
1698 ///
1699 bool tools::SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs,
1700                       llvm::opt::ArgStringList &CC1Args,
1701                       SmallVector<std::string, 8> LibraryPaths, std::string Lib,
1702                       StringRef Arch, StringRef Target, bool isBitCodeSDL,
1703                       bool postClangLink) {
1704   SmallVector<std::string, 12> SDLs;
1705 
1706   std::string LibDeviceLoc = "/libdevice";
1707   std::string LibBcPrefix = "/libbc-";
1708   std::string LibPrefix = "/lib";
1709 
1710   if (isBitCodeSDL) {
1711     // SEARCH-ORDER for Bitcode SDLs:
1712     //       libdevice/libbc-<libname>-<arch-name>-<device-type>.a
1713     //       libbc-<libname>-<arch-name>-<device-type>.a
1714     //       libdevice/libbc-<libname>-<arch-name>.a
1715     //       libbc-<libname>-<arch-name>.a
1716     //       libdevice/libbc-<libname>.a
1717     //       libbc-<libname>.a
1718     //       libdevice/lib<libname>-<arch-name>-<device-type>.bc
1719     //       lib<libname>-<arch-name>-<device-type>.bc
1720     //       libdevice/lib<libname>-<arch-name>.bc
1721     //       lib<libname>-<arch-name>.bc
1722     //       libdevice/lib<libname>.bc
1723     //       lib<libname>.bc
1724 
1725     for (StringRef Base : {LibBcPrefix, LibPrefix}) {
1726       const auto *Ext = Base.contains(LibBcPrefix) ? ".a" : ".bc";
1727 
1728       for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
1729                           Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) {
1730         SDLs.push_back(Twine(LibDeviceLoc + Base + Suffix + Ext).str());
1731         SDLs.push_back(Twine(Base + Suffix + Ext).str());
1732       }
1733     }
1734   } else {
1735     // SEARCH-ORDER for Machine-code SDLs:
1736     //    libdevice/lib<libname>-<arch-name>-<device-type>.a
1737     //    lib<libname>-<arch-name>-<device-type>.a
1738     //    libdevice/lib<libname>-<arch-name>.a
1739     //    lib<libname>-<arch-name>.a
1740 
1741     const auto *Ext = ".a";
1742 
1743     for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
1744                         Twine(Lib + "-" + Arch).str()}) {
1745       SDLs.push_back(Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str());
1746       SDLs.push_back(Twine(LibPrefix + Suffix + Ext).str());
1747     }
1748   }
1749 
1750   // The CUDA toolchain does not use a global device llvm-link before the LLVM
1751   // backend generates ptx. So currently, the use of bitcode SDL for nvptx is
1752   // only possible with post-clang-cc1 linking. Clang cc1 has a feature that
1753   // will link libraries after clang compilation while the LLVM IR is still in
1754   // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”.
1755   // This is a clang -cc1 option that is generated by the clang driver. The
1756   // option value must a full path to an existing file.
1757   bool FoundSDL = false;
1758   for (auto LPath : LibraryPaths) {
1759     for (auto SDL : SDLs) {
1760       auto FullName = Twine(LPath + SDL).str();
1761       if (llvm::sys::fs::exists(FullName)) {
1762         if (postClangLink)
1763           CC1Args.push_back("-mlink-builtin-bitcode");
1764         CC1Args.push_back(DriverArgs.MakeArgString(FullName));
1765         FoundSDL = true;
1766         break;
1767       }
1768     }
1769     if (FoundSDL)
1770       break;
1771   }
1772   return FoundSDL;
1773 }
1774 
1775 /// Search if a user provided archive file lib<libname>.a exists in any of
1776 /// the library paths. If so, add a new command to clang-offload-bundler to
1777 /// unbundle this archive and create a temporary device specific archive. Name
1778 /// of this SDL is passed to the llvm-link (for amdgcn) or to the
1779 /// clang-nvlink-wrapper (for nvptx) commands by the driver.
1780 bool tools::GetSDLFromOffloadArchive(
1781     Compilation &C, const Driver &D, const Tool &T, const JobAction &JA,
1782     const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs,
1783     llvm::opt::ArgStringList &CC1Args, SmallVector<std::string, 8> LibraryPaths,
1784     StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL,
1785     bool postClangLink) {
1786 
1787   // We don't support bitcode archive bundles for nvptx
1788   if (isBitCodeSDL && Arch.contains("nvptx"))
1789     return false;
1790 
1791   bool FoundAOB = false;
1792   SmallVector<std::string, 2> AOBFileNames;
1793   std::string ArchiveOfBundles;
1794   for (auto LPath : LibraryPaths) {
1795     ArchiveOfBundles.clear();
1796 
1797     llvm::Triple Triple(D.getTargetTriple());
1798     bool IsMSVC = Triple.isWindowsMSVCEnvironment();
1799     for (auto Prefix : {"/libdevice/", "/"}) {
1800       if (IsMSVC)
1801         AOBFileNames.push_back(Twine(LPath + Prefix + Lib + ".lib").str());
1802       AOBFileNames.push_back(Twine(LPath + Prefix + "lib" + Lib + ".a").str());
1803     }
1804 
1805     for (auto AOB : AOBFileNames) {
1806       if (llvm::sys::fs::exists(AOB)) {
1807         ArchiveOfBundles = AOB;
1808         FoundAOB = true;
1809         break;
1810       }
1811     }
1812 
1813     if (!FoundAOB)
1814       continue;
1815 
1816     StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib";
1817     std::string OutputLib = D.GetTemporaryPath(
1818         Twine(Prefix + Lib + "-" + Arch + "-" + Target).str(), "a");
1819 
1820     C.addTempFile(C.getArgs().MakeArgString(OutputLib));
1821 
1822     ArgStringList CmdArgs;
1823     SmallString<128> DeviceTriple;
1824     DeviceTriple += Action::GetOffloadKindName(JA.getOffloadingDeviceKind());
1825     DeviceTriple += '-';
1826     std::string NormalizedTriple = T.getToolChain().getTriple().normalize();
1827     DeviceTriple += NormalizedTriple;
1828     if (!Target.empty()) {
1829       DeviceTriple += '-';
1830       DeviceTriple += Target;
1831     }
1832 
1833     std::string UnbundleArg("-unbundle");
1834     std::string TypeArg("-type=a");
1835     std::string InputArg("-input=" + ArchiveOfBundles);
1836     std::string OffloadArg("-targets=" + std::string(DeviceTriple));
1837     std::string OutputArg("-output=" + OutputLib);
1838 
1839     const char *UBProgram = DriverArgs.MakeArgString(
1840         T.getToolChain().GetProgramPath("clang-offload-bundler"));
1841 
1842     ArgStringList UBArgs;
1843     UBArgs.push_back(C.getArgs().MakeArgString(UnbundleArg));
1844     UBArgs.push_back(C.getArgs().MakeArgString(TypeArg));
1845     UBArgs.push_back(C.getArgs().MakeArgString(InputArg));
1846     UBArgs.push_back(C.getArgs().MakeArgString(OffloadArg));
1847     UBArgs.push_back(C.getArgs().MakeArgString(OutputArg));
1848 
1849     // Add this flag to not exit from clang-offload-bundler if no compatible
1850     // code object is found in heterogenous archive library.
1851     std::string AdditionalArgs("-allow-missing-bundles");
1852     UBArgs.push_back(C.getArgs().MakeArgString(AdditionalArgs));
1853 
1854     // Add this flag to treat hip and hipv4 offload kinds as compatible with
1855     // openmp offload kind while extracting code objects from a heterogenous
1856     // archive library. Vice versa is also considered compatible.
1857     std::string HipCompatibleArgs("-hip-openmp-compatible");
1858     UBArgs.push_back(C.getArgs().MakeArgString(HipCompatibleArgs));
1859 
1860     C.addCommand(std::make_unique<Command>(
1861         JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs,
1862         InputInfo(&JA, C.getArgs().MakeArgString(OutputLib))));
1863     if (postClangLink)
1864       CC1Args.push_back("-mlink-builtin-bitcode");
1865 
1866     CC1Args.push_back(DriverArgs.MakeArgString(OutputLib));
1867     break;
1868   }
1869 
1870   return FoundAOB;
1871 }
1872 
1873 // Wrapper function used by driver for adding SDLs during link phase.
1874 void tools::AddStaticDeviceLibsLinking(Compilation &C, const Tool &T,
1875                                 const JobAction &JA,
1876                                 const InputInfoList &Inputs,
1877                                 const llvm::opt::ArgList &DriverArgs,
1878                                 llvm::opt::ArgStringList &CC1Args,
1879                                 StringRef Arch, StringRef Target,
1880                                 bool isBitCodeSDL, bool postClangLink) {
1881   AddStaticDeviceLibs(&C, &T, &JA, &Inputs, C.getDriver(), DriverArgs, CC1Args,
1882                       Arch, Target, isBitCodeSDL, postClangLink);
1883 }
1884 
1885 // Wrapper function used for post clang linking of bitcode SDLS for nvptx by
1886 // the CUDA toolchain.
1887 void tools::AddStaticDeviceLibsPostLinking(const Driver &D,
1888                                 const llvm::opt::ArgList &DriverArgs,
1889                                 llvm::opt::ArgStringList &CC1Args,
1890                                 StringRef Arch, StringRef Target,
1891                                 bool isBitCodeSDL, bool postClangLink) {
1892   AddStaticDeviceLibs(nullptr, nullptr, nullptr, nullptr, D, DriverArgs,
1893                       CC1Args, Arch, Target, isBitCodeSDL, postClangLink);
1894 }
1895 
1896 // User defined Static Device Libraries(SDLs) can be passed to clang for
1897 // offloading GPU compilers. Like static host libraries, the use of a SDL is
1898 // specified with the -l command line option. The primary difference between
1899 // host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs
1900 // and SEARCH-ORDER for Machine-code SDLs for the naming convention).
1901 // SDLs are of following types:
1902 //
1903 // * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files.
1904 //           For NVPTX, these libraries are post-clang linked following each
1905 //           compilation. For AMDGPU, these libraries are linked one time
1906 //           during the application link phase.
1907 //
1908 // * Machine-code SDLs: They are archive files. For NVPTX, the archive members
1909 //           contain cubin for Nvidia GPUs and are linked one time during the
1910 //           link phase by the CUDA SDK linker called nvlink.	For AMDGPU, the
1911 //           process for machine code SDLs is still in development. But they
1912 //           will be linked by the LLVM tool lld.
1913 //
1914 // * Bundled objects that contain both host and device codes: Bundled objects
1915 //           may also contain library code compiled from source. For NVPTX, the
1916 //           bundle contains cubin. For AMDGPU, the bundle contains bitcode.
1917 //
1918 // For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the
1919 // inclusion of specific SDLs such as math libraries and the OpenMP device
1920 // library libomptarget.
1921 void tools::AddStaticDeviceLibs(Compilation *C, const Tool *T,
1922                                 const JobAction *JA,
1923                                 const InputInfoList *Inputs, const Driver &D,
1924                                 const llvm::opt::ArgList &DriverArgs,
1925                                 llvm::opt::ArgStringList &CC1Args,
1926                                 StringRef Arch, StringRef Target,
1927                                 bool isBitCodeSDL, bool postClangLink) {
1928 
1929   SmallVector<std::string, 8> LibraryPaths;
1930   // Add search directories from LIBRARY_PATH env variable
1931   llvm::Optional<std::string> LibPath =
1932       llvm::sys::Process::GetEnv("LIBRARY_PATH");
1933   if (LibPath) {
1934     SmallVector<StringRef, 8> Frags;
1935     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
1936     llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
1937     for (StringRef Path : Frags)
1938       LibraryPaths.emplace_back(Path.trim());
1939   }
1940 
1941   // Add directories from user-specified -L options
1942   for (std::string Search_Dir : DriverArgs.getAllArgValues(options::OPT_L))
1943     LibraryPaths.emplace_back(Search_Dir);
1944 
1945   // Add path to lib-debug folders
1946   SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
1947   llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
1948   LibraryPaths.emplace_back(DefaultLibPath.c_str());
1949 
1950   // Build list of Static Device Libraries SDLs specified by -l option
1951   llvm::SmallSet<std::string, 16> SDLNames;
1952   static const StringRef HostOnlyArchives[] = {
1953       "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"};
1954   for (auto SDLName : DriverArgs.getAllArgValues(options::OPT_l)) {
1955     if (!HostOnlyArchives->contains(SDLName)) {
1956       SDLNames.insert(SDLName);
1957     }
1958   }
1959 
1960   // The search stops as soon as an SDL file is found. The driver then provides
1961   // the full filename of the SDL to the llvm-link or clang-nvlink-wrapper
1962   // command. If no SDL is found after searching each LINKPATH with
1963   // SEARCH-ORDER, it is possible that an archive file lib<libname>.a exists
1964   // and may contain bundled object files.
1965   for (auto SDLName : SDLNames) {
1966     // This is the only call to SDLSearch
1967     if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target,
1968                    isBitCodeSDL, postClangLink)) {
1969       GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args,
1970                                LibraryPaths, SDLName, Arch, Target,
1971                                isBitCodeSDL, postClangLink);
1972     }
1973   }
1974 }
1975 
1976 static llvm::opt::Arg *
1977 getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
1978   // The last of -mcode-object-v3, -mno-code-object-v3 and
1979   // -mcode-object-version=<version> wins.
1980   return Args.getLastArg(options::OPT_mcode_object_v3_legacy,
1981                          options::OPT_mno_code_object_v3_legacy,
1982                          options::OPT_mcode_object_version_EQ);
1983 }
1984 
1985 void tools::checkAMDGPUCodeObjectVersion(const Driver &D,
1986                                          const llvm::opt::ArgList &Args) {
1987   const unsigned MinCodeObjVer = 2;
1988   const unsigned MaxCodeObjVer = 5;
1989 
1990   // Emit warnings for legacy options even if they are overridden.
1991   if (Args.hasArg(options::OPT_mno_code_object_v3_legacy))
1992     D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3"
1993                                           << "-mcode-object-version=2";
1994 
1995   if (Args.hasArg(options::OPT_mcode_object_v3_legacy))
1996     D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3"
1997                                           << "-mcode-object-version=3";
1998 
1999   if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
2000     if (CodeObjArg->getOption().getID() ==
2001         options::OPT_mcode_object_version_EQ) {
2002       unsigned CodeObjVer = MaxCodeObjVer;
2003       auto Remnant =
2004           StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2005       if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)
2006         D.Diag(diag::err_drv_invalid_int_value)
2007             << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
2008     }
2009   }
2010 }
2011 
2012 unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D,
2013                                            const llvm::opt::ArgList &Args) {
2014   unsigned CodeObjVer = 4; // default
2015   if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
2016     if (CodeObjArg->getOption().getID() ==
2017         options::OPT_mno_code_object_v3_legacy) {
2018       CodeObjVer = 2;
2019     } else if (CodeObjArg->getOption().getID() ==
2020                options::OPT_mcode_object_v3_legacy) {
2021       CodeObjVer = 3;
2022     } else {
2023       StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2024     }
2025   }
2026   return CodeObjVer;
2027 }
2028 
2029 bool tools::haveAMDGPUCodeObjectVersionArgument(
2030     const Driver &D, const llvm::opt::ArgList &Args) {
2031   return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
2032 }
2033 
2034 void tools::addMachineOutlinerArgs(const Driver &D,
2035                                    const llvm::opt::ArgList &Args,
2036                                    llvm::opt::ArgStringList &CmdArgs,
2037                                    const llvm::Triple &Triple, bool IsLTO) {
2038   auto addArg = [&, IsLTO](const Twine &Arg) {
2039     if (IsLTO) {
2040       CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
2041     } else {
2042       CmdArgs.push_back("-mllvm");
2043       CmdArgs.push_back(Args.MakeArgString(Arg));
2044     }
2045   };
2046 
2047   if (Arg *A = Args.getLastArg(options::OPT_moutline,
2048                                options::OPT_mno_outline)) {
2049     if (A->getOption().matches(options::OPT_moutline)) {
2050       // We only support -moutline in AArch64 and ARM targets right now. If
2051       // we're not compiling for these, emit a warning and ignore the flag.
2052       // Otherwise, add the proper mllvm flags.
2053       if (!(Triple.isARM() || Triple.isThumb() ||
2054             Triple.getArch() == llvm::Triple::aarch64 ||
2055             Triple.getArch() == llvm::Triple::aarch64_32)) {
2056         D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
2057       } else {
2058         addArg(Twine("-enable-machine-outliner"));
2059       }
2060     } else {
2061       // Disable all outlining behaviour.
2062       addArg(Twine("-enable-machine-outliner=never"));
2063     }
2064   }
2065 }
2066 
2067 void tools::addOpenMPDeviceRTL(const Driver &D,
2068                                const llvm::opt::ArgList &DriverArgs,
2069                                llvm::opt::ArgStringList &CC1Args,
2070                                StringRef BitcodeSuffix,
2071                                const llvm::Triple &Triple) {
2072   SmallVector<StringRef, 8> LibraryPaths;
2073 
2074   // Add path to clang lib / lib64 folder.
2075   SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
2076   llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
2077   LibraryPaths.emplace_back(DefaultLibPath.c_str());
2078 
2079   // Add user defined library paths from LIBRARY_PATH.
2080   llvm::Optional<std::string> LibPath =
2081       llvm::sys::Process::GetEnv("LIBRARY_PATH");
2082   if (LibPath) {
2083     SmallVector<StringRef, 8> Frags;
2084     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2085     llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2086     for (StringRef Path : Frags)
2087       LibraryPaths.emplace_back(Path.trim());
2088   }
2089 
2090   OptSpecifier LibomptargetBCPathOpt =
2091       Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ
2092                         : options::OPT_libomptarget_nvptx_bc_path_EQ;
2093 
2094   StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu" : "nvptx";
2095   std::string LibOmpTargetName =
2096       ("libomptarget-" + ArchPrefix + "-" + BitcodeSuffix + ".bc").str();
2097 
2098   // First check whether user specifies bc library
2099   if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) {
2100     SmallString<128> LibOmpTargetFile(A->getValue());
2101     if (llvm::sys::fs::exists(LibOmpTargetFile) &&
2102         llvm::sys::fs::is_directory(LibOmpTargetFile)) {
2103       llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2104     }
2105 
2106     if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2107       CC1Args.push_back("-mlink-builtin-bitcode");
2108       CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2109     } else {
2110       D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
2111           << LibOmpTargetFile;
2112     }
2113   } else {
2114     bool FoundBCLibrary = false;
2115 
2116     for (StringRef LibraryPath : LibraryPaths) {
2117       SmallString<128> LibOmpTargetFile(LibraryPath);
2118       llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2119       if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2120         CC1Args.push_back("-mlink-builtin-bitcode");
2121         CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2122         FoundBCLibrary = true;
2123         break;
2124       }
2125     }
2126 
2127     if (!FoundBCLibrary)
2128       D.Diag(diag::err_drv_omp_offload_target_missingbcruntime)
2129           << LibOmpTargetName << ArchPrefix;
2130   }
2131 }
2132 void tools::addHIPRuntimeLibArgs(const ToolChain &TC,
2133                                  const llvm::opt::ArgList &Args,
2134                                  llvm::opt::ArgStringList &CmdArgs) {
2135   if (Args.hasArg(options::OPT_hip_link) &&
2136       !Args.hasArg(options::OPT_nostdlib) &&
2137       !Args.hasArg(options::OPT_no_hip_rt)) {
2138     TC.AddHIPRuntimeLibArgs(Args, CmdArgs);
2139   } else {
2140     // Claim "no HIP libraries" arguments if any
2141     for (auto Arg : Args.filtered(options::OPT_no_hip_rt)) {
2142       Arg->claim();
2143     }
2144   }
2145 }
2146