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