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