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