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   for (const auto &II : Inputs) {
149     // If the current tool chain refers to an OpenMP or HIP offloading host, we
150     // should ignore inputs that refer to OpenMP or HIP offloading devices -
151     // they will be embedded according to a proper linker script.
152     if (auto *IA = II.getAction())
153       if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
154            IA->isDeviceOffloading(Action::OFK_OpenMP)) ||
155           (JA.isHostOffloading(Action::OFK_HIP) &&
156            IA->isDeviceOffloading(Action::OFK_HIP)))
157         continue;
158 
159     if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
160       // Don't try to pass LLVM inputs unless we have native support.
161       D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
162 
163     // Add filenames immediately.
164     if (II.isFilename()) {
165       CmdArgs.push_back(II.getFilename());
166       continue;
167     }
168 
169     // Otherwise, this is a linker input argument.
170     const Arg &A = II.getInputArg();
171 
172     // Handle reserved library options.
173     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
174       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
175     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
176       TC.AddCCKextLibArgs(Args, CmdArgs);
177     else if (A.getOption().matches(options::OPT_z)) {
178       // Pass -z prefix for gcc linker compatibility.
179       A.claim();
180       A.render(Args, CmdArgs);
181     } else {
182       A.renderAsInput(Args, CmdArgs);
183     }
184   }
185 
186   // LIBRARY_PATH - included following the user specified library paths.
187   //                and only supported on native toolchains.
188   if (!TC.isCrossCompiling()) {
189     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
190   }
191 }
192 
193 void tools::AddTargetFeature(const ArgList &Args,
194                              std::vector<StringRef> &Features,
195                              OptSpecifier OnOpt, OptSpecifier OffOpt,
196                              StringRef FeatureName) {
197   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
198     if (A->getOption().matches(OnOpt))
199       Features.push_back(Args.MakeArgString("+" + FeatureName));
200     else
201       Features.push_back(Args.MakeArgString("-" + FeatureName));
202   }
203 }
204 
205 /// Get the (LLVM) name of the R600 gpu we are targeting.
206 static std::string getR600TargetGPU(const ArgList &Args) {
207   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
208     const char *GPUName = A->getValue();
209     return llvm::StringSwitch<const char *>(GPUName)
210         .Cases("rv630", "rv635", "r600")
211         .Cases("rv610", "rv620", "rs780", "rs880")
212         .Case("rv740", "rv770")
213         .Case("palm", "cedar")
214         .Cases("sumo", "sumo2", "sumo")
215         .Case("hemlock", "cypress")
216         .Case("aruba", "cayman")
217         .Default(GPUName);
218   }
219   return "";
220 }
221 
222 static std::string getLanaiTargetCPU(const ArgList &Args) {
223   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
224     return A->getValue();
225   }
226   return "";
227 }
228 
229 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
230 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
231   // If we have -mcpu=, use that.
232   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
233     StringRef CPU = A->getValue();
234 
235 #ifdef __wasm__
236     // Handle "native" by examining the host. "native" isn't meaningful when
237     // cross compiling, so only support this when the host is also WebAssembly.
238     if (CPU == "native")
239       return llvm::sys::getHostCPUName();
240 #endif
241 
242     return CPU;
243   }
244 
245   return "generic";
246 }
247 
248 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
249                               bool FromAs) {
250   Arg *A;
251 
252   switch (T.getArch()) {
253   default:
254     return "";
255 
256   case llvm::Triple::aarch64:
257   case llvm::Triple::aarch64_be:
258     return aarch64::getAArch64TargetCPU(Args, T, A);
259 
260   case llvm::Triple::arm:
261   case llvm::Triple::armeb:
262   case llvm::Triple::thumb:
263   case llvm::Triple::thumbeb: {
264     StringRef MArch, MCPU;
265     arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
266     return arm::getARMTargetCPU(MCPU, MArch, T);
267   }
268 
269   case llvm::Triple::avr:
270     if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
271       return A->getValue();
272     return "";
273 
274   case llvm::Triple::mips:
275   case llvm::Triple::mipsel:
276   case llvm::Triple::mips64:
277   case llvm::Triple::mips64el: {
278     StringRef CPUName;
279     StringRef ABIName;
280     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
281     return CPUName;
282   }
283 
284   case llvm::Triple::nvptx:
285   case llvm::Triple::nvptx64:
286     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
287       return A->getValue();
288     return "";
289 
290   case llvm::Triple::ppc:
291   case llvm::Triple::ppc64:
292   case llvm::Triple::ppc64le: {
293     std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
294     // LLVM may default to generating code for the native CPU,
295     // but, like gcc, we default to a more generic option for
296     // each architecture. (except on Darwin)
297     if (TargetCPUName.empty() && !T.isOSDarwin()) {
298       if (T.getArch() == llvm::Triple::ppc64)
299         TargetCPUName = "ppc64";
300       else if (T.getArch() == llvm::Triple::ppc64le)
301         TargetCPUName = "ppc64le";
302       else
303         TargetCPUName = "ppc";
304     }
305     return TargetCPUName;
306   }
307 
308   case llvm::Triple::bpfel:
309   case llvm::Triple::bpfeb:
310   case llvm::Triple::sparc:
311   case llvm::Triple::sparcel:
312   case llvm::Triple::sparcv9:
313     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
314       return A->getValue();
315     return "";
316 
317   case llvm::Triple::x86:
318   case llvm::Triple::x86_64:
319     return x86::getX86TargetCPU(Args, T);
320 
321   case llvm::Triple::hexagon:
322     return "hexagon" +
323            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
324 
325   case llvm::Triple::lanai:
326     return getLanaiTargetCPU(Args);
327 
328   case llvm::Triple::systemz:
329     return systemz::getSystemZTargetCPU(Args);
330 
331   case llvm::Triple::r600:
332   case llvm::Triple::amdgcn:
333     return getR600TargetGPU(Args);
334 
335   case llvm::Triple::wasm32:
336   case llvm::Triple::wasm64:
337     return getWebAssemblyTargetCPU(Args);
338   }
339 }
340 
341 unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
342   unsigned Parallelism = 0;
343   Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
344   if (LtoJobsArg &&
345       StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
346     D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
347                                             << LtoJobsArg->getValue();
348   return Parallelism;
349 }
350 
351 // CloudABI uses -ffunction-sections and -fdata-sections by default.
352 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
353   return Triple.getOS() == llvm::Triple::CloudABI;
354 }
355 
356 void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
357                           ArgStringList &CmdArgs, const InputInfo &Output,
358                           const InputInfo &Input, bool IsThinLTO) {
359   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
360   // as gold requires -plugin to come before any -plugin-opt that -Wl might
361   // forward.
362   CmdArgs.push_back("-plugin");
363 
364 #if defined(_WIN32)
365   const char *Suffix = ".dll";
366 #elif defined(__APPLE__)
367   const char *Suffix = ".dylib";
368 #else
369   const char *Suffix = ".so";
370 #endif
371 
372   SmallString<1024> Plugin;
373   llvm::sys::path::native(Twine(ToolChain.getDriver().Dir) +
374                               "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" +
375                               Suffix,
376                           Plugin);
377   CmdArgs.push_back(Args.MakeArgString(Plugin));
378 
379   // Try to pass driver level flags relevant to LTO code generation down to
380   // the plugin.
381 
382   // Handle flags for selecting CPU variants.
383   std::string CPU = getCPUName(Args, ToolChain.getTriple());
384   if (!CPU.empty())
385     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
386 
387   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
388     StringRef OOpt;
389     if (A->getOption().matches(options::OPT_O4) ||
390         A->getOption().matches(options::OPT_Ofast))
391       OOpt = "3";
392     else if (A->getOption().matches(options::OPT_O))
393       OOpt = A->getValue();
394     else if (A->getOption().matches(options::OPT_O0))
395       OOpt = "0";
396     if (!OOpt.empty())
397       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
398   }
399 
400   if (Args.hasArg(options::OPT_gsplit_dwarf)) {
401     CmdArgs.push_back(
402         Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
403             Output.getFilename() + "_dwo"));
404   }
405 
406   if (IsThinLTO)
407     CmdArgs.push_back("-plugin-opt=thinlto");
408 
409   if (unsigned Parallelism = getLTOParallelism(Args, ToolChain.getDriver()))
410     CmdArgs.push_back(
411         Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
412 
413   // If an explicit debugger tuning argument appeared, pass it along.
414   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
415                                options::OPT_ggdbN_Group)) {
416     if (A->getOption().matches(options::OPT_glldb))
417       CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
418     else if (A->getOption().matches(options::OPT_gsce))
419       CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
420     else
421       CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
422   }
423 
424   bool UseSeparateSections =
425       isUseSeparateSections(ToolChain.getEffectiveTriple());
426 
427   if (Args.hasFlag(options::OPT_ffunction_sections,
428                    options::OPT_fno_function_sections, UseSeparateSections)) {
429     CmdArgs.push_back("-plugin-opt=-function-sections");
430   }
431 
432   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
433                    UseSeparateSections)) {
434     CmdArgs.push_back("-plugin-opt=-data-sections");
435   }
436 
437   if (Arg *A = getLastProfileSampleUseArg(Args)) {
438     StringRef FName = A->getValue();
439     if (!llvm::sys::fs::exists(FName))
440       ToolChain.getDriver().Diag(diag::err_drv_no_such_file) << FName;
441     else
442       CmdArgs.push_back(
443           Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
444   }
445 
446   auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
447                                            options::OPT_fcs_profile_generate_EQ,
448                                            options::OPT_fno_profile_generate);
449   if (CSPGOGenerateArg &&
450       CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
451     CSPGOGenerateArg = nullptr;
452 
453   auto *ProfileUseArg = getLastProfileUseArg(Args);
454 
455   if (CSPGOGenerateArg) {
456     CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate"));
457     if (CSPGOGenerateArg->getOption().matches(
458             options::OPT_fcs_profile_generate_EQ)) {
459       SmallString<128> Path(CSPGOGenerateArg->getValue());
460       llvm::sys::path::append(Path, "default_%m.profraw");
461       CmdArgs.push_back(
462           Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path));
463     } else
464       CmdArgs.push_back(
465           Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw"));
466   } else if (ProfileUseArg) {
467     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") +
468                                          ProfileUseArg->getValue()));
469   }
470 
471   // Need this flag to turn on new pass manager via Gold plugin.
472   if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager,
473                    options::OPT_fno_experimental_new_pass_manager,
474                    /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER)) {
475     CmdArgs.push_back("-plugin-opt=new-pass-manager");
476   }
477 
478   // Setup statistics file output.
479   SmallString<128> StatsFile =
480       getStatsFileName(Args, Output, Input, ToolChain.getDriver());
481   if (!StatsFile.empty())
482     CmdArgs.push_back(
483         Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
484 }
485 
486 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
487                                  ArgStringList &CmdArgs) {
488   if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
489                     options::OPT_fno_rtlib_add_rpath, false))
490     return;
491 
492   std::string CandidateRPath = TC.getArchSpecificLibPath();
493   if (TC.getVFS().exists(CandidateRPath)) {
494     CmdArgs.push_back("-rpath");
495     CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
496   }
497 }
498 
499 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
500                              const ArgList &Args, bool IsOffloadingHost,
501                              bool GompNeedsRT) {
502   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
503                     options::OPT_fno_openmp, false))
504     return false;
505 
506   switch (TC.getDriver().getOpenMPRuntime(Args)) {
507   case Driver::OMPRT_OMP:
508     CmdArgs.push_back("-lomp");
509     break;
510   case Driver::OMPRT_GOMP:
511     CmdArgs.push_back("-lgomp");
512 
513     if (GompNeedsRT)
514       CmdArgs.push_back("-lrt");
515     break;
516   case Driver::OMPRT_IOMP5:
517     CmdArgs.push_back("-liomp5");
518     break;
519   case Driver::OMPRT_Unknown:
520     // Already diagnosed.
521     return false;
522   }
523 
524   if (IsOffloadingHost)
525     CmdArgs.push_back("-lomptarget");
526 
527   addArchSpecificRPath(TC, Args, CmdArgs);
528 
529   return true;
530 }
531 
532 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
533                                 ArgStringList &CmdArgs, StringRef Sanitizer,
534                                 bool IsShared, bool IsWhole) {
535   // Wrap any static runtimes that must be forced into executable in
536   // whole-archive.
537   if (IsWhole) CmdArgs.push_back("--whole-archive");
538   CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
539   if (IsWhole) CmdArgs.push_back("--no-whole-archive");
540 
541   if (IsShared) {
542     addArchSpecificRPath(TC, Args, CmdArgs);
543   }
544 }
545 
546 // Tries to use a file with the list of dynamic symbols that need to be exported
547 // from the runtime library. Returns true if the file was found.
548 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
549                                     ArgStringList &CmdArgs,
550                                     StringRef Sanitizer) {
551   // Solaris ld defaults to --export-dynamic behaviour but doesn't support
552   // the option, so don't try to pass it.
553   if (TC.getTriple().getOS() == llvm::Triple::Solaris)
554     return true;
555   // Myriad is static linking only.  Furthermore, some versions of its
556   // linker have the bug where --export-dynamic overrides -static, so
557   // don't use --export-dynamic on that platform.
558   if (TC.getTriple().getVendor() == llvm::Triple::Myriad)
559     return true;
560   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
561   if (llvm::sys::fs::exists(SanRT + ".syms")) {
562     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
563     return true;
564   }
565   return false;
566 }
567 
568 static void addSanitizerLibPath(const ToolChain &TC, const ArgList &Args,
569                                 ArgStringList &CmdArgs, StringRef Name) {
570   for (const auto &LibPath : TC.getLibraryPaths()) {
571     if (!LibPath.empty()) {
572       SmallString<128> P(LibPath);
573       llvm::sys::path::append(P, Name);
574       if (TC.getVFS().exists(P))
575         CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + P));
576     }
577   }
578 }
579 
580 void tools::addSanitizerPathLibArgs(const ToolChain &TC, const ArgList &Args,
581                                     ArgStringList &CmdArgs) {
582   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
583   if (SanArgs.needsAsanRt()) {
584     addSanitizerLibPath(TC, Args, CmdArgs, "asan");
585   }
586   if (SanArgs.needsHwasanRt()) {
587     addSanitizerLibPath(TC, Args, CmdArgs, "hwasan");
588   }
589   if (SanArgs.needsLsanRt()) {
590     addSanitizerLibPath(TC, Args, CmdArgs, "lsan");
591   }
592   if (SanArgs.needsMsanRt()) {
593     addSanitizerLibPath(TC, Args, CmdArgs, "msan");
594   }
595   if (SanArgs.needsTsanRt()) {
596     addSanitizerLibPath(TC, Args, CmdArgs, "tsan");
597   }
598 }
599 
600 
601 
602 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
603                                      ArgStringList &CmdArgs) {
604   // Force linking against the system libraries sanitizers depends on
605   // (see PR15823 why this is necessary).
606   CmdArgs.push_back("--no-as-needed");
607   // There's no libpthread or librt on RTEMS & Android.
608   if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
609       !TC.getTriple().isAndroid()) {
610     CmdArgs.push_back("-lpthread");
611     if (!TC.getTriple().isOSOpenBSD())
612       CmdArgs.push_back("-lrt");
613   }
614   CmdArgs.push_back("-lm");
615   // There's no libdl on all OSes.
616   if (!TC.getTriple().isOSFreeBSD() &&
617       !TC.getTriple().isOSNetBSD() &&
618       !TC.getTriple().isOSOpenBSD() &&
619        TC.getTriple().getOS() != llvm::Triple::RTEMS)
620     CmdArgs.push_back("-ldl");
621   // Required for backtrace on some OSes
622   if (TC.getTriple().isOSFreeBSD() ||
623       TC.getTriple().isOSNetBSD())
624     CmdArgs.push_back("-lexecinfo");
625 }
626 
627 static void
628 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
629                          SmallVectorImpl<StringRef> &SharedRuntimes,
630                          SmallVectorImpl<StringRef> &StaticRuntimes,
631                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
632                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
633                          SmallVectorImpl<StringRef> &RequiredSymbols) {
634   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
635   // Collect shared runtimes.
636   if (SanArgs.needsSharedRt()) {
637     if (SanArgs.needsAsanRt()) {
638       SharedRuntimes.push_back("asan");
639       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
640         HelperStaticRuntimes.push_back("asan-preinit");
641     }
642     if (SanArgs.needsUbsanRt()) {
643       if (SanArgs.requiresMinimalRuntime())
644         SharedRuntimes.push_back("ubsan_minimal");
645       else
646         SharedRuntimes.push_back("ubsan_standalone");
647     }
648     if (SanArgs.needsScudoRt()) {
649       if (SanArgs.requiresMinimalRuntime())
650         SharedRuntimes.push_back("scudo_minimal");
651       else
652         SharedRuntimes.push_back("scudo");
653     }
654     if (SanArgs.needsHwasanRt())
655       SharedRuntimes.push_back("hwasan");
656   }
657 
658   // The stats_client library is also statically linked into DSOs.
659   if (SanArgs.needsStatsRt())
660     StaticRuntimes.push_back("stats_client");
661 
662   // Collect static runtimes.
663   if (Args.hasArg(options::OPT_shared) || SanArgs.needsSharedRt()) {
664     // Don't link static runtimes into DSOs or if -shared-libasan.
665     return;
666   }
667   if (SanArgs.needsAsanRt()) {
668     StaticRuntimes.push_back("asan");
669     if (SanArgs.linkCXXRuntimes())
670       StaticRuntimes.push_back("asan_cxx");
671   }
672 
673   if (SanArgs.needsHwasanRt()) {
674     StaticRuntimes.push_back("hwasan");
675     if (SanArgs.linkCXXRuntimes())
676       StaticRuntimes.push_back("hwasan_cxx");
677   }
678   if (SanArgs.needsDfsanRt())
679     StaticRuntimes.push_back("dfsan");
680   if (SanArgs.needsLsanRt())
681     StaticRuntimes.push_back("lsan");
682   if (SanArgs.needsMsanRt()) {
683     StaticRuntimes.push_back("msan");
684     if (SanArgs.linkCXXRuntimes())
685       StaticRuntimes.push_back("msan_cxx");
686   }
687   if (SanArgs.needsTsanRt()) {
688     StaticRuntimes.push_back("tsan");
689     if (SanArgs.linkCXXRuntimes())
690       StaticRuntimes.push_back("tsan_cxx");
691   }
692   if (SanArgs.needsUbsanRt()) {
693     if (SanArgs.requiresMinimalRuntime()) {
694       StaticRuntimes.push_back("ubsan_minimal");
695     } else {
696       StaticRuntimes.push_back("ubsan_standalone");
697       if (SanArgs.linkCXXRuntimes())
698         StaticRuntimes.push_back("ubsan_standalone_cxx");
699     }
700   }
701   if (SanArgs.needsSafeStackRt()) {
702     NonWholeStaticRuntimes.push_back("safestack");
703     RequiredSymbols.push_back("__safestack_init");
704   }
705   if (SanArgs.needsCfiRt())
706     StaticRuntimes.push_back("cfi");
707   if (SanArgs.needsCfiDiagRt()) {
708     StaticRuntimes.push_back("cfi_diag");
709     if (SanArgs.linkCXXRuntimes())
710       StaticRuntimes.push_back("ubsan_standalone_cxx");
711   }
712   if (SanArgs.needsStatsRt()) {
713     NonWholeStaticRuntimes.push_back("stats");
714     RequiredSymbols.push_back("__sanitizer_stats_register");
715   }
716   if (SanArgs.needsEsanRt())
717     StaticRuntimes.push_back("esan");
718   if (SanArgs.needsScudoRt()) {
719     if (SanArgs.requiresMinimalRuntime()) {
720       StaticRuntimes.push_back("scudo_minimal");
721       if (SanArgs.linkCXXRuntimes())
722         StaticRuntimes.push_back("scudo_cxx_minimal");
723     } else {
724       StaticRuntimes.push_back("scudo");
725       if (SanArgs.linkCXXRuntimes())
726         StaticRuntimes.push_back("scudo_cxx");
727     }
728   }
729 }
730 
731 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
732 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
733 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
734                                  ArgStringList &CmdArgs) {
735   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
736       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
737   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
738                            NonWholeStaticRuntimes, HelperStaticRuntimes,
739                            RequiredSymbols);
740 
741   // Inject libfuzzer dependencies.
742   if (TC.getSanitizerArgs().needsFuzzer()
743       && !Args.hasArg(options::OPT_shared)) {
744 
745     addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
746     if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
747       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
748   }
749 
750   for (auto RT : SharedRuntimes)
751     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
752   for (auto RT : HelperStaticRuntimes)
753     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
754   bool AddExportDynamic = false;
755   for (auto RT : StaticRuntimes) {
756     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
757     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
758   }
759   for (auto RT : NonWholeStaticRuntimes) {
760     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
761     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
762   }
763   for (auto S : RequiredSymbols) {
764     CmdArgs.push_back("-u");
765     CmdArgs.push_back(Args.MakeArgString(S));
766   }
767   // If there is a static runtime with no dynamic list, force all the symbols
768   // to be dynamic to be sure we export sanitizer interface functions.
769   if (AddExportDynamic)
770     CmdArgs.push_back("--export-dynamic");
771 
772   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
773   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
774     CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
775 
776   return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
777 }
778 
779 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
780   if (Args.hasArg(options::OPT_shared))
781     return false;
782 
783   if (TC.getXRayArgs().needsXRayRt()) {
784     CmdArgs.push_back("-whole-archive");
785     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
786     for (const auto &Mode : TC.getXRayArgs().modeList())
787       CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
788     CmdArgs.push_back("-no-whole-archive");
789     return true;
790   }
791 
792   return false;
793 }
794 
795 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
796   CmdArgs.push_back("--no-as-needed");
797   CmdArgs.push_back("-lpthread");
798   if (!TC.getTriple().isOSOpenBSD())
799     CmdArgs.push_back("-lrt");
800   CmdArgs.push_back("-lm");
801 
802   if (!TC.getTriple().isOSFreeBSD() &&
803       !TC.getTriple().isOSNetBSD() &&
804       !TC.getTriple().isOSOpenBSD())
805     CmdArgs.push_back("-ldl");
806 }
807 
808 bool tools::areOptimizationsEnabled(const ArgList &Args) {
809   // Find the last -O arg and see if it is non-zero.
810   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
811     return !A->getOption().matches(options::OPT_O0);
812   // Defaults to -O0.
813   return false;
814 }
815 
816 const char *tools::SplitDebugName(const ArgList &Args,
817                                   const InputInfo &Output) {
818   SmallString<128> F(Output.isFilename()
819                          ? Output.getFilename()
820                          : llvm::sys::path::stem(Output.getBaseInput()));
821 
822   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
823     if (StringRef(A->getValue()) == "single")
824       return Args.MakeArgString(F);
825 
826   llvm::sys::path::replace_extension(F, "dwo");
827   return Args.MakeArgString(F);
828 }
829 
830 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
831                            const JobAction &JA, const ArgList &Args,
832                            const InputInfo &Output, const char *OutFile) {
833   ArgStringList ExtractArgs;
834   ExtractArgs.push_back("--extract-dwo");
835 
836   ArgStringList StripArgs;
837   StripArgs.push_back("--strip-dwo");
838 
839   // Grabbing the output of the earlier compile step.
840   StripArgs.push_back(Output.getFilename());
841   ExtractArgs.push_back(Output.getFilename());
842   ExtractArgs.push_back(OutFile);
843 
844   const char *Exec =
845       Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
846   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
847 
848   // First extract the dwo sections.
849   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
850 
851   // Then remove them from the original .o file.
852   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
853 }
854 
855 // Claim options we don't want to warn if they are unused. We do this for
856 // options that build systems might add but are unused when assembling or only
857 // running the preprocessor for example.
858 void tools::claimNoWarnArgs(const ArgList &Args) {
859   // Don't warn about unused -f(no-)?lto.  This can happen when we're
860   // preprocessing, precompiling or assembling.
861   Args.ClaimAllArgs(options::OPT_flto_EQ);
862   Args.ClaimAllArgs(options::OPT_flto);
863   Args.ClaimAllArgs(options::OPT_fno_lto);
864 }
865 
866 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
867   auto *ProfileUseArg = Args.getLastArg(
868       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
869       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
870       options::OPT_fno_profile_instr_use);
871 
872   if (ProfileUseArg &&
873       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
874     ProfileUseArg = nullptr;
875 
876   return ProfileUseArg;
877 }
878 
879 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
880   auto *ProfileSampleUseArg = Args.getLastArg(
881       options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
882       options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
883       options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
884 
885   if (ProfileSampleUseArg &&
886       (ProfileSampleUseArg->getOption().matches(
887            options::OPT_fno_profile_sample_use) ||
888        ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
889     return nullptr;
890 
891   return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
892                          options::OPT_fauto_profile_EQ);
893 }
894 
895 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
896 /// smooshes them together with platform defaults, to decide whether
897 /// this compile should be using PIC mode or not. Returns a tuple of
898 /// (RelocationModel, PICLevel, IsPIE).
899 std::tuple<llvm::Reloc::Model, unsigned, bool>
900 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
901   const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
902   const llvm::Triple &Triple = ToolChain.getTriple();
903 
904   bool PIE = ToolChain.isPIEDefault();
905   bool PIC = PIE || ToolChain.isPICDefault();
906   // The Darwin/MachO default to use PIC does not apply when using -static.
907   if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
908     PIE = PIC = false;
909   bool IsPICLevelTwo = PIC;
910 
911   bool KernelOrKext =
912       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
913 
914   // Android-specific defaults for PIC/PIE
915   if (Triple.isAndroid()) {
916     switch (Triple.getArch()) {
917     case llvm::Triple::arm:
918     case llvm::Triple::armeb:
919     case llvm::Triple::thumb:
920     case llvm::Triple::thumbeb:
921     case llvm::Triple::aarch64:
922     case llvm::Triple::mips:
923     case llvm::Triple::mipsel:
924     case llvm::Triple::mips64:
925     case llvm::Triple::mips64el:
926       PIC = true; // "-fpic"
927       break;
928 
929     case llvm::Triple::x86:
930     case llvm::Triple::x86_64:
931       PIC = true; // "-fPIC"
932       IsPICLevelTwo = true;
933       break;
934 
935     default:
936       break;
937     }
938   }
939 
940   // OpenBSD-specific defaults for PIE
941   if (Triple.isOSOpenBSD()) {
942     switch (ToolChain.getArch()) {
943     case llvm::Triple::arm:
944     case llvm::Triple::aarch64:
945     case llvm::Triple::mips64:
946     case llvm::Triple::mips64el:
947     case llvm::Triple::x86:
948     case llvm::Triple::x86_64:
949       IsPICLevelTwo = false; // "-fpie"
950       break;
951 
952     case llvm::Triple::ppc:
953     case llvm::Triple::sparc:
954     case llvm::Triple::sparcel:
955     case llvm::Triple::sparcv9:
956       IsPICLevelTwo = true; // "-fPIE"
957       break;
958 
959     default:
960       break;
961     }
962   }
963 
964   // AMDGPU-specific defaults for PIC.
965   if (Triple.getArch() == llvm::Triple::amdgcn)
966     PIC = true;
967 
968   // The last argument relating to either PIC or PIE wins, and no
969   // other argument is used. If the last argument is any flavor of the
970   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
971   // option implicitly enables PIC at the same level.
972   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
973                                     options::OPT_fpic, options::OPT_fno_pic,
974                                     options::OPT_fPIE, options::OPT_fno_PIE,
975                                     options::OPT_fpie, options::OPT_fno_pie);
976   if (Triple.isOSWindows() && LastPICArg &&
977       LastPICArg ==
978           Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
979                           options::OPT_fPIE, options::OPT_fpie)) {
980     ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
981         << LastPICArg->getSpelling() << Triple.str();
982     if (Triple.getArch() == llvm::Triple::x86_64)
983       return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
984     return std::make_tuple(llvm::Reloc::Static, 0U, false);
985   }
986 
987   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
988   // is forced, then neither PIC nor PIE flags will have no effect.
989   if (!ToolChain.isPICDefaultForced()) {
990     if (LastPICArg) {
991       Option O = LastPICArg->getOption();
992       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
993           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
994         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
995         PIC =
996             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
997         IsPICLevelTwo =
998             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
999       } else {
1000         PIE = PIC = false;
1001         if (EffectiveTriple.isPS4CPU()) {
1002           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1003           StringRef Model = ModelArg ? ModelArg->getValue() : "";
1004           if (Model != "kernel") {
1005             PIC = true;
1006             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
1007                 << LastPICArg->getSpelling();
1008           }
1009         }
1010       }
1011     }
1012   }
1013 
1014   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
1015   // PIC level would've been set to level 1, force it back to level 2 PIC
1016   // instead.
1017   if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
1018     IsPICLevelTwo |= ToolChain.isPICDefault();
1019 
1020   // This kernel flags are a trump-card: they will disable PIC/PIE
1021   // generation, independent of the argument order.
1022   if (KernelOrKext &&
1023       ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1024        !EffectiveTriple.isWatchOS()))
1025     PIC = PIE = false;
1026 
1027   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1028     // This is a very special mode. It trumps the other modes, almost no one
1029     // uses it, and it isn't even valid on any OS but Darwin.
1030     if (!Triple.isOSDarwin())
1031       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1032           << A->getSpelling() << Triple.str();
1033 
1034     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1035 
1036     // Only a forced PIC mode can cause the actual compile to have PIC defines
1037     // etc., no flags are sufficient. This behavior was selected to closely
1038     // match that of llvm-gcc and Apple GCC before that.
1039     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1040 
1041     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1042   }
1043 
1044   bool EmbeddedPISupported;
1045   switch (Triple.getArch()) {
1046     case llvm::Triple::arm:
1047     case llvm::Triple::armeb:
1048     case llvm::Triple::thumb:
1049     case llvm::Triple::thumbeb:
1050       EmbeddedPISupported = true;
1051       break;
1052     default:
1053       EmbeddedPISupported = false;
1054       break;
1055   }
1056 
1057   bool ROPI = false, RWPI = false;
1058   Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1059   if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1060     if (!EmbeddedPISupported)
1061       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1062           << LastROPIArg->getSpelling() << Triple.str();
1063     ROPI = true;
1064   }
1065   Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1066   if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1067     if (!EmbeddedPISupported)
1068       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1069           << LastRWPIArg->getSpelling() << Triple.str();
1070     RWPI = true;
1071   }
1072 
1073   // ROPI and RWPI are not compatible with PIC or PIE.
1074   if ((ROPI || RWPI) && (PIC || PIE))
1075     ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1076 
1077   if (Triple.isMIPS()) {
1078     StringRef CPUName;
1079     StringRef ABIName;
1080     mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1081     // When targeting the N64 ABI, PIC is the default, except in the case
1082     // when the -mno-abicalls option is used. In that case we exit
1083     // at next check regardless of PIC being set below.
1084     if (ABIName == "n64")
1085       PIC = true;
1086     // When targettng MIPS with -mno-abicalls, it's always static.
1087     if(Args.hasArg(options::OPT_mno_abicalls))
1088       return std::make_tuple(llvm::Reloc::Static, 0U, false);
1089     // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1090     // does not use PIC level 2 for historical reasons.
1091     IsPICLevelTwo = false;
1092   }
1093 
1094   if (PIC)
1095     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1096 
1097   llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1098   if (ROPI && RWPI)
1099     RelocM = llvm::Reloc::ROPI_RWPI;
1100   else if (ROPI)
1101     RelocM = llvm::Reloc::ROPI;
1102   else if (RWPI)
1103     RelocM = llvm::Reloc::RWPI;
1104 
1105   return std::make_tuple(RelocM, 0U, false);
1106 }
1107 
1108 // `-falign-functions` indicates that the functions should be aligned to a
1109 // 16-byte boundary.
1110 //
1111 // `-falign-functions=1` is the same as `-fno-align-functions`.
1112 //
1113 // The scalar `n` in `-falign-functions=n` must be an integral value between
1114 // [0, 65536].  If the value is not a power-of-two, it will be rounded up to
1115 // the nearest power-of-two.
1116 //
1117 // If we return `0`, the frontend will default to the backend's preferred
1118 // alignment.
1119 //
1120 // NOTE: icc only allows values between [0, 4096].  icc uses `-falign-functions`
1121 // to mean `-falign-functions=16`.  GCC defaults to the backend's preferred
1122 // alignment.  For unaligned functions, we default to the backend's preferred
1123 // alignment.
1124 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1125                                        const ArgList &Args) {
1126   const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1127                                  options::OPT_falign_functions_EQ,
1128                                  options::OPT_fno_align_functions);
1129   if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1130     return 0;
1131 
1132   if (A->getOption().matches(options::OPT_falign_functions))
1133     return 0;
1134 
1135   unsigned Value = 0;
1136   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1137     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1138         << A->getAsString(Args) << A->getValue();
1139   return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1140 }
1141 
1142 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1143                              ArgStringList &CmdArgs) {
1144   llvm::Reloc::Model RelocationModel;
1145   unsigned PICLevel;
1146   bool IsPIE;
1147   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1148 
1149   if (RelocationModel != llvm::Reloc::Static)
1150     CmdArgs.push_back("-KPIC");
1151 }
1152 
1153 /// Determine whether Objective-C automated reference counting is
1154 /// enabled.
1155 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1156   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1157 }
1158 
1159 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
1160                       ArgStringList &CmdArgs, const ArgList &Args) {
1161   bool isAndroid = Triple.isAndroid();
1162   bool isCygMing = Triple.isOSCygMing();
1163   bool IsIAMCU = Triple.isOSIAMCU();
1164   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
1165                       Args.hasArg(options::OPT_static) ||
1166                       Args.hasArg(options::OPT_static_pie);
1167 
1168   bool SharedLibgcc = Args.hasArg(options::OPT_shared_libgcc);
1169   bool UnspecifiedLibgcc = !StaticLibgcc && !SharedLibgcc;
1170 
1171   // Gcc adds libgcc arguments in various ways:
1172   //
1173   // gcc <none>:     -lgcc --as-needed -lgcc_s --no-as-needed
1174   // g++ <none>:                       -lgcc_s               -lgcc
1175   // gcc shared:                       -lgcc_s               -lgcc
1176   // g++ shared:                       -lgcc_s               -lgcc
1177   // gcc static:     -lgcc             -lgcc_eh
1178   // g++ static:     -lgcc             -lgcc_eh
1179   // gcc static-pie: -lgcc             -lgcc_eh
1180   // g++ static-pie: -lgcc             -lgcc_eh
1181   //
1182   // Also, certain targets need additional adjustments.
1183 
1184   bool LibGccFirst = (D.CCCIsCC() && UnspecifiedLibgcc) || StaticLibgcc;
1185   if (LibGccFirst)
1186     CmdArgs.push_back("-lgcc");
1187 
1188   bool AsNeeded = D.CCCIsCC() && UnspecifiedLibgcc && !isAndroid && !isCygMing;
1189   if (AsNeeded)
1190     CmdArgs.push_back("--as-needed");
1191 
1192   if ((UnspecifiedLibgcc || SharedLibgcc) && !isAndroid)
1193     CmdArgs.push_back("-lgcc_s");
1194 
1195   else if (StaticLibgcc && !isAndroid && !IsIAMCU)
1196     CmdArgs.push_back("-lgcc_eh");
1197 
1198   if (AsNeeded)
1199     CmdArgs.push_back("--no-as-needed");
1200 
1201   if (!LibGccFirst)
1202     CmdArgs.push_back("-lgcc");
1203 
1204   // According to Android ABI, we have to link with libdl if we are
1205   // linking with non-static libgcc.
1206   //
1207   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
1208   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
1209   if (isAndroid && !StaticLibgcc)
1210     CmdArgs.push_back("-ldl");
1211 }
1212 
1213 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1214                            ArgStringList &CmdArgs, const ArgList &Args) {
1215   // Make use of compiler-rt if --rtlib option is used
1216   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1217 
1218   switch (RLT) {
1219   case ToolChain::RLT_CompilerRT:
1220     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
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.getTriple(), 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::F_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::F_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