xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Driver/ToolChains/CommonArgs.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg 
97330f729Sjoerg #include "CommonArgs.h"
107330f729Sjoerg #include "Arch/AArch64.h"
117330f729Sjoerg #include "Arch/ARM.h"
12*e038c9c4Sjoerg #include "Arch/M68k.h"
137330f729Sjoerg #include "Arch/Mips.h"
147330f729Sjoerg #include "Arch/PPC.h"
157330f729Sjoerg #include "Arch/SystemZ.h"
16*e038c9c4Sjoerg #include "Arch/VE.h"
177330f729Sjoerg #include "Arch/X86.h"
187330f729Sjoerg #include "HIP.h"
197330f729Sjoerg #include "Hexagon.h"
207330f729Sjoerg #include "InputInfo.h"
217330f729Sjoerg #include "clang/Basic/CharInfo.h"
227330f729Sjoerg #include "clang/Basic/LangOptions.h"
237330f729Sjoerg #include "clang/Basic/ObjCRuntime.h"
247330f729Sjoerg #include "clang/Basic/Version.h"
257330f729Sjoerg #include "clang/Config/config.h"
267330f729Sjoerg #include "clang/Driver/Action.h"
277330f729Sjoerg #include "clang/Driver/Compilation.h"
287330f729Sjoerg #include "clang/Driver/Driver.h"
297330f729Sjoerg #include "clang/Driver/DriverDiagnostic.h"
307330f729Sjoerg #include "clang/Driver/Job.h"
317330f729Sjoerg #include "clang/Driver/Options.h"
327330f729Sjoerg #include "clang/Driver/SanitizerArgs.h"
337330f729Sjoerg #include "clang/Driver/ToolChain.h"
347330f729Sjoerg #include "clang/Driver/Util.h"
357330f729Sjoerg #include "clang/Driver/XRayArgs.h"
367330f729Sjoerg #include "llvm/ADT/STLExtras.h"
377330f729Sjoerg #include "llvm/ADT/SmallString.h"
387330f729Sjoerg #include "llvm/ADT/StringExtras.h"
397330f729Sjoerg #include "llvm/ADT/StringSwitch.h"
407330f729Sjoerg #include "llvm/ADT/Twine.h"
41*e038c9c4Sjoerg #include "llvm/Config/llvm-config.h"
427330f729Sjoerg #include "llvm/Option/Arg.h"
437330f729Sjoerg #include "llvm/Option/ArgList.h"
447330f729Sjoerg #include "llvm/Option/Option.h"
457330f729Sjoerg #include "llvm/Support/CodeGen.h"
467330f729Sjoerg #include "llvm/Support/Compression.h"
477330f729Sjoerg #include "llvm/Support/Debug.h"
487330f729Sjoerg #include "llvm/Support/ErrorHandling.h"
497330f729Sjoerg #include "llvm/Support/FileSystem.h"
507330f729Sjoerg #include "llvm/Support/Host.h"
517330f729Sjoerg #include "llvm/Support/Path.h"
527330f729Sjoerg #include "llvm/Support/Process.h"
537330f729Sjoerg #include "llvm/Support/Program.h"
547330f729Sjoerg #include "llvm/Support/ScopedPrinter.h"
557330f729Sjoerg #include "llvm/Support/TargetParser.h"
56*e038c9c4Sjoerg #include "llvm/Support/Threading.h"
577330f729Sjoerg #include "llvm/Support/VirtualFileSystem.h"
587330f729Sjoerg #include "llvm/Support/YAMLParser.h"
597330f729Sjoerg 
607330f729Sjoerg using namespace clang::driver;
617330f729Sjoerg using namespace clang::driver::tools;
627330f729Sjoerg using namespace clang;
637330f729Sjoerg using namespace llvm::opt;
647330f729Sjoerg 
renderRpassOptions(const ArgList & Args,ArgStringList & CmdArgs)65*e038c9c4Sjoerg static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs) {
66*e038c9c4Sjoerg   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
67*e038c9c4Sjoerg     CmdArgs.push_back(Args.MakeArgString(Twine("--plugin-opt=-pass-remarks=") +
68*e038c9c4Sjoerg                                          A->getValue()));
69*e038c9c4Sjoerg 
70*e038c9c4Sjoerg   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
71*e038c9c4Sjoerg     CmdArgs.push_back(Args.MakeArgString(
72*e038c9c4Sjoerg         Twine("--plugin-opt=-pass-remarks-missed=") + A->getValue()));
73*e038c9c4Sjoerg 
74*e038c9c4Sjoerg   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
75*e038c9c4Sjoerg     CmdArgs.push_back(Args.MakeArgString(
76*e038c9c4Sjoerg         Twine("--plugin-opt=-pass-remarks-analysis=") + A->getValue()));
77*e038c9c4Sjoerg }
78*e038c9c4Sjoerg 
renderRemarksOptions(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple,const InputInfo & Input,const InputInfo & Output)79*e038c9c4Sjoerg static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
80*e038c9c4Sjoerg                                  const llvm::Triple &Triple,
81*e038c9c4Sjoerg                                  const InputInfo &Input,
82*e038c9c4Sjoerg                                  const InputInfo &Output) {
83*e038c9c4Sjoerg   StringRef Format = "yaml";
84*e038c9c4Sjoerg   if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
85*e038c9c4Sjoerg     Format = A->getValue();
86*e038c9c4Sjoerg 
87*e038c9c4Sjoerg   SmallString<128> F;
88*e038c9c4Sjoerg   const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
89*e038c9c4Sjoerg   if (A)
90*e038c9c4Sjoerg     F = A->getValue();
91*e038c9c4Sjoerg   else if (Output.isFilename())
92*e038c9c4Sjoerg     F = Output.getFilename();
93*e038c9c4Sjoerg 
94*e038c9c4Sjoerg   assert(!F.empty() && "Cannot determine remarks output name.");
95*e038c9c4Sjoerg   // Append "opt.ld.<format>" to the end of the file name.
96*e038c9c4Sjoerg   CmdArgs.push_back(
97*e038c9c4Sjoerg       Args.MakeArgString(Twine("--plugin-opt=opt-remarks-filename=") + F +
98*e038c9c4Sjoerg                          Twine(".opt.ld.") + Format));
99*e038c9c4Sjoerg 
100*e038c9c4Sjoerg   if (const Arg *A =
101*e038c9c4Sjoerg           Args.getLastArg(options::OPT_foptimization_record_passes_EQ))
102*e038c9c4Sjoerg     CmdArgs.push_back(Args.MakeArgString(
103*e038c9c4Sjoerg         Twine("--plugin-opt=opt-remarks-passes=") + A->getValue()));
104*e038c9c4Sjoerg 
105*e038c9c4Sjoerg   CmdArgs.push_back(Args.MakeArgString(
106*e038c9c4Sjoerg       Twine("--plugin-opt=opt-remarks-format=") + Format.data()));
107*e038c9c4Sjoerg }
108*e038c9c4Sjoerg 
renderRemarksHotnessOptions(const ArgList & Args,ArgStringList & CmdArgs)109*e038c9c4Sjoerg static void renderRemarksHotnessOptions(const ArgList &Args,
110*e038c9c4Sjoerg                                         ArgStringList &CmdArgs) {
111*e038c9c4Sjoerg   if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
112*e038c9c4Sjoerg                    options::OPT_fno_diagnostics_show_hotness, false))
113*e038c9c4Sjoerg     CmdArgs.push_back("--plugin-opt=opt-remarks-with-hotness");
114*e038c9c4Sjoerg 
115*e038c9c4Sjoerg   if (const Arg *A =
116*e038c9c4Sjoerg           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ))
117*e038c9c4Sjoerg     CmdArgs.push_back(Args.MakeArgString(
118*e038c9c4Sjoerg         Twine("--plugin-opt=opt-remarks-hotness-threshold=") + A->getValue()));
119*e038c9c4Sjoerg }
120*e038c9c4Sjoerg 
addPathIfExists(const Driver & D,const Twine & Path,ToolChain::path_list & Paths)1217330f729Sjoerg void tools::addPathIfExists(const Driver &D, const Twine &Path,
1227330f729Sjoerg                             ToolChain::path_list &Paths) {
1237330f729Sjoerg   if (D.getVFS().exists(Path))
1247330f729Sjoerg     Paths.push_back(Path.str());
1257330f729Sjoerg }
1267330f729Sjoerg 
handleTargetFeaturesGroup(const ArgList & Args,std::vector<StringRef> & Features,OptSpecifier Group)1277330f729Sjoerg void tools::handleTargetFeaturesGroup(const ArgList &Args,
1287330f729Sjoerg                                       std::vector<StringRef> &Features,
1297330f729Sjoerg                                       OptSpecifier Group) {
1307330f729Sjoerg   for (const Arg *A : Args.filtered(Group)) {
1317330f729Sjoerg     StringRef Name = A->getOption().getName();
1327330f729Sjoerg     A->claim();
1337330f729Sjoerg 
1347330f729Sjoerg     // Skip over "-m".
1357330f729Sjoerg     assert(Name.startswith("m") && "Invalid feature name.");
1367330f729Sjoerg     Name = Name.substr(1);
1377330f729Sjoerg 
1387330f729Sjoerg     bool IsNegative = Name.startswith("no-");
1397330f729Sjoerg     if (IsNegative)
1407330f729Sjoerg       Name = Name.substr(3);
1417330f729Sjoerg     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1427330f729Sjoerg   }
1437330f729Sjoerg }
1447330f729Sjoerg 
145*e038c9c4Sjoerg std::vector<StringRef>
unifyTargetFeatures(const std::vector<StringRef> & Features)146*e038c9c4Sjoerg tools::unifyTargetFeatures(const std::vector<StringRef> &Features) {
147*e038c9c4Sjoerg   std::vector<StringRef> UnifiedFeatures;
148*e038c9c4Sjoerg   // Find the last of each feature.
149*e038c9c4Sjoerg   llvm::StringMap<unsigned> LastOpt;
150*e038c9c4Sjoerg   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
151*e038c9c4Sjoerg     StringRef Name = Features[I];
152*e038c9c4Sjoerg     assert(Name[0] == '-' || Name[0] == '+');
153*e038c9c4Sjoerg     LastOpt[Name.drop_front(1)] = I;
154*e038c9c4Sjoerg   }
155*e038c9c4Sjoerg 
156*e038c9c4Sjoerg   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
157*e038c9c4Sjoerg     // If this feature was overridden, ignore it.
158*e038c9c4Sjoerg     StringRef Name = Features[I];
159*e038c9c4Sjoerg     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
160*e038c9c4Sjoerg     assert(LastI != LastOpt.end());
161*e038c9c4Sjoerg     unsigned Last = LastI->second;
162*e038c9c4Sjoerg     if (Last != I)
163*e038c9c4Sjoerg       continue;
164*e038c9c4Sjoerg 
165*e038c9c4Sjoerg     UnifiedFeatures.push_back(Name);
166*e038c9c4Sjoerg   }
167*e038c9c4Sjoerg   return UnifiedFeatures;
168*e038c9c4Sjoerg }
169*e038c9c4Sjoerg 
addDirectoryList(const ArgList & Args,ArgStringList & CmdArgs,const char * ArgName,const char * EnvVar)1707330f729Sjoerg void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
1717330f729Sjoerg                              const char *ArgName, const char *EnvVar) {
1727330f729Sjoerg   const char *DirList = ::getenv(EnvVar);
1737330f729Sjoerg   bool CombinedArg = false;
1747330f729Sjoerg 
1757330f729Sjoerg   if (!DirList)
1767330f729Sjoerg     return; // Nothing to do.
1777330f729Sjoerg 
1787330f729Sjoerg   StringRef Name(ArgName);
179*e038c9c4Sjoerg   if (Name.equals("-I") || Name.equals("-L") || Name.empty())
1807330f729Sjoerg     CombinedArg = true;
1817330f729Sjoerg 
1827330f729Sjoerg   StringRef Dirs(DirList);
1837330f729Sjoerg   if (Dirs.empty()) // Empty string should not add '.'.
1847330f729Sjoerg     return;
1857330f729Sjoerg 
1867330f729Sjoerg   StringRef::size_type Delim;
1877330f729Sjoerg   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
1887330f729Sjoerg     if (Delim == 0) { // Leading colon.
1897330f729Sjoerg       if (CombinedArg) {
1907330f729Sjoerg         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
1917330f729Sjoerg       } else {
1927330f729Sjoerg         CmdArgs.push_back(ArgName);
1937330f729Sjoerg         CmdArgs.push_back(".");
1947330f729Sjoerg       }
1957330f729Sjoerg     } else {
1967330f729Sjoerg       if (CombinedArg) {
1977330f729Sjoerg         CmdArgs.push_back(
1987330f729Sjoerg             Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
1997330f729Sjoerg       } else {
2007330f729Sjoerg         CmdArgs.push_back(ArgName);
2017330f729Sjoerg         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
2027330f729Sjoerg       }
2037330f729Sjoerg     }
2047330f729Sjoerg     Dirs = Dirs.substr(Delim + 1);
2057330f729Sjoerg   }
2067330f729Sjoerg 
2077330f729Sjoerg   if (Dirs.empty()) { // Trailing colon.
2087330f729Sjoerg     if (CombinedArg) {
2097330f729Sjoerg       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
2107330f729Sjoerg     } else {
2117330f729Sjoerg       CmdArgs.push_back(ArgName);
2127330f729Sjoerg       CmdArgs.push_back(".");
2137330f729Sjoerg     }
2147330f729Sjoerg   } else { // Add the last path.
2157330f729Sjoerg     if (CombinedArg) {
2167330f729Sjoerg       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
2177330f729Sjoerg     } else {
2187330f729Sjoerg       CmdArgs.push_back(ArgName);
2197330f729Sjoerg       CmdArgs.push_back(Args.MakeArgString(Dirs));
2207330f729Sjoerg     }
2217330f729Sjoerg   }
2227330f729Sjoerg }
2237330f729Sjoerg 
AddLinkerInputs(const ToolChain & TC,const InputInfoList & Inputs,const ArgList & Args,ArgStringList & CmdArgs,const JobAction & JA)2247330f729Sjoerg void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
2257330f729Sjoerg                             const ArgList &Args, ArgStringList &CmdArgs,
2267330f729Sjoerg                             const JobAction &JA) {
2277330f729Sjoerg   const Driver &D = TC.getDriver();
2287330f729Sjoerg 
2297330f729Sjoerg   // Add extra linker input arguments which are not treated as inputs
2307330f729Sjoerg   // (constructed via -Xarch_).
2317330f729Sjoerg   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
2327330f729Sjoerg 
2337330f729Sjoerg   // LIBRARY_PATH are included before user inputs and only supported on native
2347330f729Sjoerg   // toolchains.
2357330f729Sjoerg   if (!TC.isCrossCompiling())
2367330f729Sjoerg     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
2377330f729Sjoerg 
2387330f729Sjoerg   for (const auto &II : Inputs) {
239*e038c9c4Sjoerg     // If the current tool chain refers to an OpenMP offloading host, we
240*e038c9c4Sjoerg     // should ignore inputs that refer to OpenMP offloading devices -
2417330f729Sjoerg     // they will be embedded according to a proper linker script.
2427330f729Sjoerg     if (auto *IA = II.getAction())
2437330f729Sjoerg       if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
244*e038c9c4Sjoerg            IA->isDeviceOffloading(Action::OFK_OpenMP)))
2457330f729Sjoerg         continue;
2467330f729Sjoerg 
2477330f729Sjoerg     if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
2487330f729Sjoerg       // Don't try to pass LLVM inputs unless we have native support.
2497330f729Sjoerg       D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
2507330f729Sjoerg 
2517330f729Sjoerg     // Add filenames immediately.
2527330f729Sjoerg     if (II.isFilename()) {
2537330f729Sjoerg       CmdArgs.push_back(II.getFilename());
2547330f729Sjoerg       continue;
2557330f729Sjoerg     }
2567330f729Sjoerg 
2577330f729Sjoerg     // Otherwise, this is a linker input argument.
2587330f729Sjoerg     const Arg &A = II.getInputArg();
2597330f729Sjoerg 
2607330f729Sjoerg     // Handle reserved library options.
2617330f729Sjoerg     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
2627330f729Sjoerg       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
2637330f729Sjoerg     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
2647330f729Sjoerg       TC.AddCCKextLibArgs(Args, CmdArgs);
2657330f729Sjoerg     else if (A.getOption().matches(options::OPT_z)) {
2667330f729Sjoerg       // Pass -z prefix for gcc linker compatibility.
2677330f729Sjoerg       A.claim();
2687330f729Sjoerg       A.render(Args, CmdArgs);
2697330f729Sjoerg     } else {
2707330f729Sjoerg       A.renderAsInput(Args, CmdArgs);
2717330f729Sjoerg     }
2727330f729Sjoerg   }
2737330f729Sjoerg }
2747330f729Sjoerg 
addLinkerCompressDebugSectionsOption(const ToolChain & TC,const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs)275*e038c9c4Sjoerg void tools::addLinkerCompressDebugSectionsOption(
276*e038c9c4Sjoerg     const ToolChain &TC, const llvm::opt::ArgList &Args,
277*e038c9c4Sjoerg     llvm::opt::ArgStringList &CmdArgs) {
278*e038c9c4Sjoerg   // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi
279*e038c9c4Sjoerg   // whereas zlib is an alias to zlib-gabi. Therefore -gz=none|zlib|zlib-gnu
280*e038c9c4Sjoerg   // are translated to --compress-debug-sections=none|zlib|zlib-gnu.
281*e038c9c4Sjoerg   // -gz is not translated since ld --compress-debug-sections option requires an
282*e038c9c4Sjoerg   // argument.
283*e038c9c4Sjoerg   if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) {
284*e038c9c4Sjoerg     StringRef V = A->getValue();
285*e038c9c4Sjoerg     if (V == "none" || V == "zlib" || V == "zlib-gnu")
286*e038c9c4Sjoerg       CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V));
287*e038c9c4Sjoerg     else
288*e038c9c4Sjoerg       TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
289*e038c9c4Sjoerg           << A->getOption().getName() << V;
290*e038c9c4Sjoerg   }
291*e038c9c4Sjoerg }
292*e038c9c4Sjoerg 
AddTargetFeature(const ArgList & Args,std::vector<StringRef> & Features,OptSpecifier OnOpt,OptSpecifier OffOpt,StringRef FeatureName)2937330f729Sjoerg void tools::AddTargetFeature(const ArgList &Args,
2947330f729Sjoerg                              std::vector<StringRef> &Features,
2957330f729Sjoerg                              OptSpecifier OnOpt, OptSpecifier OffOpt,
2967330f729Sjoerg                              StringRef FeatureName) {
2977330f729Sjoerg   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
2987330f729Sjoerg     if (A->getOption().matches(OnOpt))
2997330f729Sjoerg       Features.push_back(Args.MakeArgString("+" + FeatureName));
3007330f729Sjoerg     else
3017330f729Sjoerg       Features.push_back(Args.MakeArgString("-" + FeatureName));
3027330f729Sjoerg   }
3037330f729Sjoerg }
3047330f729Sjoerg 
305*e038c9c4Sjoerg /// Get the (LLVM) name of the AMDGPU gpu we are targeting.
getAMDGPUTargetGPU(const llvm::Triple & T,const ArgList & Args)306*e038c9c4Sjoerg static std::string getAMDGPUTargetGPU(const llvm::Triple &T,
307*e038c9c4Sjoerg                                       const ArgList &Args) {
3087330f729Sjoerg   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
309*e038c9c4Sjoerg     auto GPUName = getProcessorFromTargetID(T, A->getValue());
310*e038c9c4Sjoerg     return llvm::StringSwitch<std::string>(GPUName)
3117330f729Sjoerg         .Cases("rv630", "rv635", "r600")
3127330f729Sjoerg         .Cases("rv610", "rv620", "rs780", "rs880")
3137330f729Sjoerg         .Case("rv740", "rv770")
3147330f729Sjoerg         .Case("palm", "cedar")
3157330f729Sjoerg         .Cases("sumo", "sumo2", "sumo")
3167330f729Sjoerg         .Case("hemlock", "cypress")
3177330f729Sjoerg         .Case("aruba", "cayman")
318*e038c9c4Sjoerg         .Default(GPUName.str());
3197330f729Sjoerg   }
3207330f729Sjoerg   return "";
3217330f729Sjoerg }
3227330f729Sjoerg 
getLanaiTargetCPU(const ArgList & Args)3237330f729Sjoerg static std::string getLanaiTargetCPU(const ArgList &Args) {
3247330f729Sjoerg   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
3257330f729Sjoerg     return A->getValue();
3267330f729Sjoerg   }
3277330f729Sjoerg   return "";
3287330f729Sjoerg }
3297330f729Sjoerg 
3307330f729Sjoerg /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
getWebAssemblyTargetCPU(const ArgList & Args)3317330f729Sjoerg static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
3327330f729Sjoerg   // If we have -mcpu=, use that.
3337330f729Sjoerg   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
3347330f729Sjoerg     StringRef CPU = A->getValue();
3357330f729Sjoerg 
3367330f729Sjoerg #ifdef __wasm__
3377330f729Sjoerg     // Handle "native" by examining the host. "native" isn't meaningful when
3387330f729Sjoerg     // cross compiling, so only support this when the host is also WebAssembly.
3397330f729Sjoerg     if (CPU == "native")
3407330f729Sjoerg       return llvm::sys::getHostCPUName();
3417330f729Sjoerg #endif
3427330f729Sjoerg 
3437330f729Sjoerg     return CPU;
3447330f729Sjoerg   }
3457330f729Sjoerg 
3467330f729Sjoerg   return "generic";
3477330f729Sjoerg }
3487330f729Sjoerg 
getCPUName(const ArgList & Args,const llvm::Triple & T,bool FromAs)3497330f729Sjoerg std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
3507330f729Sjoerg                               bool FromAs) {
3517330f729Sjoerg   Arg *A;
3527330f729Sjoerg 
3537330f729Sjoerg   switch (T.getArch()) {
3547330f729Sjoerg   default:
3557330f729Sjoerg     return "";
3567330f729Sjoerg 
3577330f729Sjoerg   case llvm::Triple::aarch64:
358*e038c9c4Sjoerg   case llvm::Triple::aarch64_32:
3597330f729Sjoerg   case llvm::Triple::aarch64_be:
3607330f729Sjoerg     return aarch64::getAArch64TargetCPU(Args, T, A);
3617330f729Sjoerg 
3627330f729Sjoerg   case llvm::Triple::arm:
3637330f729Sjoerg   case llvm::Triple::armeb:
3647330f729Sjoerg   case llvm::Triple::thumb:
3657330f729Sjoerg   case llvm::Triple::thumbeb: {
3667330f729Sjoerg     StringRef MArch, MCPU;
3677330f729Sjoerg     arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
3687330f729Sjoerg     return arm::getARMTargetCPU(MCPU, MArch, T);
3697330f729Sjoerg   }
3707330f729Sjoerg 
3717330f729Sjoerg   case llvm::Triple::avr:
3727330f729Sjoerg     if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
3737330f729Sjoerg       return A->getValue();
3747330f729Sjoerg     return "";
3757330f729Sjoerg 
376*e038c9c4Sjoerg   case llvm::Triple::m68k:
377*e038c9c4Sjoerg     return m68k::getM68kTargetCPU(Args);
378*e038c9c4Sjoerg 
3797330f729Sjoerg   case llvm::Triple::mips:
3807330f729Sjoerg   case llvm::Triple::mipsel:
3817330f729Sjoerg   case llvm::Triple::mips64:
3827330f729Sjoerg   case llvm::Triple::mips64el: {
3837330f729Sjoerg     StringRef CPUName;
3847330f729Sjoerg     StringRef ABIName;
3857330f729Sjoerg     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
386*e038c9c4Sjoerg     return std::string(CPUName);
3877330f729Sjoerg   }
3887330f729Sjoerg 
3897330f729Sjoerg   case llvm::Triple::nvptx:
3907330f729Sjoerg   case llvm::Triple::nvptx64:
3917330f729Sjoerg     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
3927330f729Sjoerg       return A->getValue();
3937330f729Sjoerg     return "";
3947330f729Sjoerg 
3957330f729Sjoerg   case llvm::Triple::ppc:
396*e038c9c4Sjoerg   case llvm::Triple::ppcle:
3977330f729Sjoerg   case llvm::Triple::ppc64:
3987330f729Sjoerg   case llvm::Triple::ppc64le: {
3997330f729Sjoerg     std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
4007330f729Sjoerg     // LLVM may default to generating code for the native CPU,
4017330f729Sjoerg     // but, like gcc, we default to a more generic option for
402*e038c9c4Sjoerg     // each architecture. (except on AIX)
403*e038c9c4Sjoerg     if (!TargetCPUName.empty())
404*e038c9c4Sjoerg       return TargetCPUName;
405*e038c9c4Sjoerg 
406*e038c9c4Sjoerg     if (T.isOSAIX()) {
407*e038c9c4Sjoerg       unsigned major, minor, unused_micro;
408*e038c9c4Sjoerg       T.getOSVersion(major, minor, unused_micro);
409*e038c9c4Sjoerg       // The minimal arch level moved from pwr4 for AIX7.1 to
410*e038c9c4Sjoerg       // pwr7 for AIX7.2.
411*e038c9c4Sjoerg       TargetCPUName =
412*e038c9c4Sjoerg           (major < 7 || (major == 7 && minor < 2)) ? "pwr4" : "pwr7";
413*e038c9c4Sjoerg     } else if (T.getArch() == llvm::Triple::ppc64le)
4147330f729Sjoerg       TargetCPUName = "ppc64le";
415*e038c9c4Sjoerg     else if (T.getArch() == llvm::Triple::ppc64)
416*e038c9c4Sjoerg       TargetCPUName = "ppc64";
4177330f729Sjoerg     else
4187330f729Sjoerg       TargetCPUName = "ppc";
419*e038c9c4Sjoerg 
4207330f729Sjoerg     return TargetCPUName;
4217330f729Sjoerg   }
422*e038c9c4Sjoerg   case llvm::Triple::riscv32:
423*e038c9c4Sjoerg   case llvm::Triple::riscv64:
424*e038c9c4Sjoerg     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
425*e038c9c4Sjoerg       return A->getValue();
426*e038c9c4Sjoerg     return "";
4277330f729Sjoerg 
4287330f729Sjoerg   case llvm::Triple::bpfel:
4297330f729Sjoerg   case llvm::Triple::bpfeb:
4307330f729Sjoerg   case llvm::Triple::sparc:
4317330f729Sjoerg   case llvm::Triple::sparcel:
4327330f729Sjoerg   case llvm::Triple::sparcv9:
4337330f729Sjoerg     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
4347330f729Sjoerg       return A->getValue();
435*e038c9c4Sjoerg     if (T.getArch() == llvm::Triple::sparc && T.isOSSolaris())
436*e038c9c4Sjoerg       return "v9";
4377330f729Sjoerg     return "";
4387330f729Sjoerg 
4397330f729Sjoerg   case llvm::Triple::x86:
4407330f729Sjoerg   case llvm::Triple::x86_64:
4417330f729Sjoerg     return x86::getX86TargetCPU(Args, T);
4427330f729Sjoerg 
4437330f729Sjoerg   case llvm::Triple::hexagon:
4447330f729Sjoerg     return "hexagon" +
4457330f729Sjoerg            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
4467330f729Sjoerg 
4477330f729Sjoerg   case llvm::Triple::lanai:
4487330f729Sjoerg     return getLanaiTargetCPU(Args);
4497330f729Sjoerg 
4507330f729Sjoerg   case llvm::Triple::systemz:
4517330f729Sjoerg     return systemz::getSystemZTargetCPU(Args);
4527330f729Sjoerg 
4537330f729Sjoerg   case llvm::Triple::r600:
4547330f729Sjoerg   case llvm::Triple::amdgcn:
455*e038c9c4Sjoerg     return getAMDGPUTargetGPU(T, Args);
4567330f729Sjoerg 
4577330f729Sjoerg   case llvm::Triple::wasm32:
4587330f729Sjoerg   case llvm::Triple::wasm64:
459*e038c9c4Sjoerg     return std::string(getWebAssemblyTargetCPU(Args));
4607330f729Sjoerg   }
4617330f729Sjoerg }
4627330f729Sjoerg 
getLTOParallelism(const ArgList & Args,const Driver & D)463*e038c9c4Sjoerg llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
4647330f729Sjoerg   Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
465*e038c9c4Sjoerg   if (!LtoJobsArg)
466*e038c9c4Sjoerg     return {};
467*e038c9c4Sjoerg   if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue()))
468*e038c9c4Sjoerg     D.Diag(diag::err_drv_invalid_int_value)
469*e038c9c4Sjoerg         << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
470*e038c9c4Sjoerg   return LtoJobsArg->getValue();
4717330f729Sjoerg }
4727330f729Sjoerg 
4737330f729Sjoerg // CloudABI uses -ffunction-sections and -fdata-sections by default.
isUseSeparateSections(const llvm::Triple & Triple)4747330f729Sjoerg bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
4757330f729Sjoerg   return Triple.getOS() == llvm::Triple::CloudABI;
4767330f729Sjoerg }
4777330f729Sjoerg 
addLTOOptions(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfo & Input,bool IsThinLTO)478*e038c9c4Sjoerg void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
4797330f729Sjoerg                           ArgStringList &CmdArgs, const InputInfo &Output,
4807330f729Sjoerg                           const InputInfo &Input, bool IsThinLTO) {
481*e038c9c4Sjoerg   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
482*e038c9c4Sjoerg   const Driver &D = ToolChain.getDriver();
483*e038c9c4Sjoerg   if (llvm::sys::path::filename(Linker) != "ld.lld" &&
484*e038c9c4Sjoerg       llvm::sys::path::stem(Linker) != "ld.lld") {
485*e038c9c4Sjoerg     // Tell the linker to load the plugin. This has to come before
486*e038c9c4Sjoerg     // AddLinkerInputs as gold requires -plugin to come before any -plugin-opt
487*e038c9c4Sjoerg     // that -Wl might forward.
4887330f729Sjoerg     CmdArgs.push_back("-plugin");
4897330f729Sjoerg 
4907330f729Sjoerg #if defined(_WIN32)
4917330f729Sjoerg     const char *Suffix = ".dll";
4927330f729Sjoerg #elif defined(__APPLE__)
4937330f729Sjoerg     const char *Suffix = ".dylib";
4947330f729Sjoerg #else
4957330f729Sjoerg     const char *Suffix = ".so";
4967330f729Sjoerg #endif
4977330f729Sjoerg 
4987330f729Sjoerg     SmallString<1024> Plugin;
499*e038c9c4Sjoerg     llvm::sys::path::native(
500*e038c9c4Sjoerg         Twine(D.Dir) + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" + Suffix,
5017330f729Sjoerg         Plugin);
5027330f729Sjoerg     CmdArgs.push_back(Args.MakeArgString(Plugin));
503*e038c9c4Sjoerg   }
5047330f729Sjoerg 
5057330f729Sjoerg   // Try to pass driver level flags relevant to LTO code generation down to
5067330f729Sjoerg   // the plugin.
5077330f729Sjoerg 
5087330f729Sjoerg   // Handle flags for selecting CPU variants.
5097330f729Sjoerg   std::string CPU = getCPUName(Args, ToolChain.getTriple());
5107330f729Sjoerg   if (!CPU.empty())
5117330f729Sjoerg     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
5127330f729Sjoerg 
5137330f729Sjoerg   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
514*e038c9c4Sjoerg     // The optimization level matches
515*e038c9c4Sjoerg     // CompilerInvocation.cpp:getOptimizationLevel().
5167330f729Sjoerg     StringRef OOpt;
5177330f729Sjoerg     if (A->getOption().matches(options::OPT_O4) ||
5187330f729Sjoerg         A->getOption().matches(options::OPT_Ofast))
5197330f729Sjoerg       OOpt = "3";
520*e038c9c4Sjoerg     else if (A->getOption().matches(options::OPT_O)) {
5217330f729Sjoerg       OOpt = A->getValue();
522*e038c9c4Sjoerg       if (OOpt == "g")
523*e038c9c4Sjoerg         OOpt = "1";
524*e038c9c4Sjoerg       else if (OOpt == "s" || OOpt == "z")
525*e038c9c4Sjoerg         OOpt = "2";
526*e038c9c4Sjoerg     } else if (A->getOption().matches(options::OPT_O0))
5277330f729Sjoerg       OOpt = "0";
5287330f729Sjoerg     if (!OOpt.empty())
5297330f729Sjoerg       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
5307330f729Sjoerg   }
5317330f729Sjoerg 
5327330f729Sjoerg   if (Args.hasArg(options::OPT_gsplit_dwarf)) {
5337330f729Sjoerg     CmdArgs.push_back(
5347330f729Sjoerg         Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
5357330f729Sjoerg             Output.getFilename() + "_dwo"));
5367330f729Sjoerg   }
5377330f729Sjoerg 
5387330f729Sjoerg   if (IsThinLTO)
5397330f729Sjoerg     CmdArgs.push_back("-plugin-opt=thinlto");
5407330f729Sjoerg 
541*e038c9c4Sjoerg   StringRef Parallelism = getLTOParallelism(Args, D);
542*e038c9c4Sjoerg   if (!Parallelism.empty())
5437330f729Sjoerg     CmdArgs.push_back(
5447330f729Sjoerg         Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
5457330f729Sjoerg 
5467330f729Sjoerg   // If an explicit debugger tuning argument appeared, pass it along.
5477330f729Sjoerg   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
5487330f729Sjoerg                                options::OPT_ggdbN_Group)) {
5497330f729Sjoerg     if (A->getOption().matches(options::OPT_glldb))
5507330f729Sjoerg       CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
5517330f729Sjoerg     else if (A->getOption().matches(options::OPT_gsce))
5527330f729Sjoerg       CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
553*e038c9c4Sjoerg     else if (A->getOption().matches(options::OPT_gdbx))
554*e038c9c4Sjoerg       CmdArgs.push_back("-plugin-opt=-debugger-tune=dbx");
5557330f729Sjoerg     else
5567330f729Sjoerg       CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
5577330f729Sjoerg   }
5587330f729Sjoerg 
5597330f729Sjoerg   bool UseSeparateSections =
5607330f729Sjoerg       isUseSeparateSections(ToolChain.getEffectiveTriple());
5617330f729Sjoerg 
5627330f729Sjoerg   if (Args.hasFlag(options::OPT_ffunction_sections,
5637330f729Sjoerg                    options::OPT_fno_function_sections, UseSeparateSections)) {
5647330f729Sjoerg     CmdArgs.push_back("-plugin-opt=-function-sections");
5657330f729Sjoerg   }
5667330f729Sjoerg 
5677330f729Sjoerg   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
5687330f729Sjoerg                    UseSeparateSections)) {
5697330f729Sjoerg     CmdArgs.push_back("-plugin-opt=-data-sections");
5707330f729Sjoerg   }
5717330f729Sjoerg 
5727330f729Sjoerg   if (Arg *A = getLastProfileSampleUseArg(Args)) {
5737330f729Sjoerg     StringRef FName = A->getValue();
5747330f729Sjoerg     if (!llvm::sys::fs::exists(FName))
575*e038c9c4Sjoerg       D.Diag(diag::err_drv_no_such_file) << FName;
5767330f729Sjoerg     else
5777330f729Sjoerg       CmdArgs.push_back(
5787330f729Sjoerg           Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
5797330f729Sjoerg   }
5807330f729Sjoerg 
5817330f729Sjoerg   auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
5827330f729Sjoerg                                            options::OPT_fcs_profile_generate_EQ,
5837330f729Sjoerg                                            options::OPT_fno_profile_generate);
5847330f729Sjoerg   if (CSPGOGenerateArg &&
5857330f729Sjoerg       CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
5867330f729Sjoerg     CSPGOGenerateArg = nullptr;
5877330f729Sjoerg 
5887330f729Sjoerg   auto *ProfileUseArg = getLastProfileUseArg(Args);
5897330f729Sjoerg 
5907330f729Sjoerg   if (CSPGOGenerateArg) {
5917330f729Sjoerg     CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate"));
5927330f729Sjoerg     if (CSPGOGenerateArg->getOption().matches(
5937330f729Sjoerg             options::OPT_fcs_profile_generate_EQ)) {
5947330f729Sjoerg       SmallString<128> Path(CSPGOGenerateArg->getValue());
5957330f729Sjoerg       llvm::sys::path::append(Path, "default_%m.profraw");
5967330f729Sjoerg       CmdArgs.push_back(
5977330f729Sjoerg           Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path));
5987330f729Sjoerg     } else
5997330f729Sjoerg       CmdArgs.push_back(
6007330f729Sjoerg           Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw"));
6017330f729Sjoerg   } else if (ProfileUseArg) {
6027330f729Sjoerg     SmallString<128> Path(
6037330f729Sjoerg         ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
6047330f729Sjoerg     if (Path.empty() || llvm::sys::fs::is_directory(Path))
6057330f729Sjoerg       llvm::sys::path::append(Path, "default.profdata");
6067330f729Sjoerg     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") +
6077330f729Sjoerg                                          Path));
6087330f729Sjoerg   }
6097330f729Sjoerg 
610*e038c9c4Sjoerg   // Pass an option to enable/disable the new pass manager.
611*e038c9c4Sjoerg   if (auto *A = Args.getLastArg(options::OPT_flegacy_pass_manager,
612*e038c9c4Sjoerg                                 options::OPT_fno_legacy_pass_manager)) {
613*e038c9c4Sjoerg     if (A->getOption().matches(options::OPT_flegacy_pass_manager))
614*e038c9c4Sjoerg       CmdArgs.push_back("-plugin-opt=legacy-pass-manager");
615*e038c9c4Sjoerg     else
6167330f729Sjoerg       CmdArgs.push_back("-plugin-opt=new-pass-manager");
6177330f729Sjoerg   }
6187330f729Sjoerg 
619*e038c9c4Sjoerg   // Pass an option to enable pseudo probe emission.
620*e038c9c4Sjoerg   if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
621*e038c9c4Sjoerg                    options::OPT_fno_pseudo_probe_for_profiling, false))
622*e038c9c4Sjoerg     CmdArgs.push_back("-plugin-opt=pseudo-probe-for-profiling");
623*e038c9c4Sjoerg 
6247330f729Sjoerg   // Setup statistics file output.
625*e038c9c4Sjoerg   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
6267330f729Sjoerg   if (!StatsFile.empty())
6277330f729Sjoerg     CmdArgs.push_back(
6287330f729Sjoerg         Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
6297330f729Sjoerg 
630*e038c9c4Sjoerg   addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true);
6317330f729Sjoerg 
632*e038c9c4Sjoerg   // Handle remark diagnostics on screen options: '-Rpass-*'.
633*e038c9c4Sjoerg   renderRpassOptions(Args, CmdArgs);
634*e038c9c4Sjoerg 
635*e038c9c4Sjoerg   // Handle serialized remarks options: '-fsave-optimization-record'
636*e038c9c4Sjoerg   // and '-foptimization-record-*'.
637*e038c9c4Sjoerg   if (willEmitRemarks(Args))
638*e038c9c4Sjoerg     renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input,
639*e038c9c4Sjoerg                          Output);
640*e038c9c4Sjoerg 
641*e038c9c4Sjoerg   // Handle remarks hotness/threshold related options.
642*e038c9c4Sjoerg   renderRemarksHotnessOptions(Args, CmdArgs);
643*e038c9c4Sjoerg 
644*e038c9c4Sjoerg   addMachineOutlinerArgs(D, Args, CmdArgs, ToolChain.getEffectiveTriple(),
645*e038c9c4Sjoerg                          /*IsLTO=*/true);
6467330f729Sjoerg }
6477330f729Sjoerg 
addArchSpecificRPath(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)6487330f729Sjoerg void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
6497330f729Sjoerg                                  ArgStringList &CmdArgs) {
650*e038c9c4Sjoerg   // Enable -frtlib-add-rpath by default for the case of VE.
651*e038c9c4Sjoerg   const bool IsVE = TC.getTriple().isVE();
652*e038c9c4Sjoerg   bool DefaultValue = IsVE;
6537330f729Sjoerg   if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
654*e038c9c4Sjoerg                     options::OPT_fno_rtlib_add_rpath, DefaultValue))
6557330f729Sjoerg     return;
6567330f729Sjoerg 
6577330f729Sjoerg   std::string CandidateRPath = TC.getArchSpecificLibPath();
6587330f729Sjoerg   if (TC.getVFS().exists(CandidateRPath)) {
6597330f729Sjoerg     CmdArgs.push_back("-rpath");
6607330f729Sjoerg     CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
6617330f729Sjoerg   }
6627330f729Sjoerg }
6637330f729Sjoerg 
addOpenMPRuntime(ArgStringList & CmdArgs,const ToolChain & TC,const ArgList & Args,bool ForceStaticHostRuntime,bool IsOffloadingHost,bool GompNeedsRT)6647330f729Sjoerg bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
6657330f729Sjoerg                              const ArgList &Args, bool ForceStaticHostRuntime,
6667330f729Sjoerg                              bool IsOffloadingHost, bool GompNeedsRT) {
6677330f729Sjoerg   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6687330f729Sjoerg                     options::OPT_fno_openmp, false))
6697330f729Sjoerg     return false;
6707330f729Sjoerg 
6717330f729Sjoerg   Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
6727330f729Sjoerg 
6737330f729Sjoerg   if (RTKind == Driver::OMPRT_Unknown)
6747330f729Sjoerg     // Already diagnosed.
6757330f729Sjoerg     return false;
6767330f729Sjoerg 
6777330f729Sjoerg   if (ForceStaticHostRuntime)
6787330f729Sjoerg     CmdArgs.push_back("-Bstatic");
6797330f729Sjoerg 
6807330f729Sjoerg   switch (RTKind) {
6817330f729Sjoerg   case Driver::OMPRT_OMP:
6827330f729Sjoerg     CmdArgs.push_back("-lomp");
6837330f729Sjoerg     break;
6847330f729Sjoerg   case Driver::OMPRT_GOMP:
6857330f729Sjoerg     CmdArgs.push_back("-lgomp");
6867330f729Sjoerg     break;
6877330f729Sjoerg   case Driver::OMPRT_IOMP5:
6887330f729Sjoerg     CmdArgs.push_back("-liomp5");
6897330f729Sjoerg     break;
6907330f729Sjoerg   case Driver::OMPRT_Unknown:
6917330f729Sjoerg     break;
6927330f729Sjoerg   }
6937330f729Sjoerg 
6947330f729Sjoerg   if (ForceStaticHostRuntime)
6957330f729Sjoerg     CmdArgs.push_back("-Bdynamic");
6967330f729Sjoerg 
6977330f729Sjoerg   if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
6987330f729Sjoerg       CmdArgs.push_back("-lrt");
6997330f729Sjoerg 
7007330f729Sjoerg   if (IsOffloadingHost)
7017330f729Sjoerg     CmdArgs.push_back("-lomptarget");
7027330f729Sjoerg 
7037330f729Sjoerg   addArchSpecificRPath(TC, Args, CmdArgs);
7047330f729Sjoerg 
7057330f729Sjoerg   return true;
7067330f729Sjoerg }
7077330f729Sjoerg 
addSanitizerRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer,bool IsShared,bool IsWhole)7087330f729Sjoerg static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
7097330f729Sjoerg                                 ArgStringList &CmdArgs, StringRef Sanitizer,
7107330f729Sjoerg                                 bool IsShared, bool IsWhole) {
7117330f729Sjoerg   // Wrap any static runtimes that must be forced into executable in
7127330f729Sjoerg   // whole-archive.
7137330f729Sjoerg   if (IsWhole) CmdArgs.push_back("--whole-archive");
7147330f729Sjoerg   CmdArgs.push_back(TC.getCompilerRTArgString(
7157330f729Sjoerg       Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
7167330f729Sjoerg   if (IsWhole) CmdArgs.push_back("--no-whole-archive");
7177330f729Sjoerg 
7187330f729Sjoerg   if (IsShared) {
7197330f729Sjoerg     addArchSpecificRPath(TC, Args, CmdArgs);
7207330f729Sjoerg   }
7217330f729Sjoerg }
7227330f729Sjoerg 
7237330f729Sjoerg // Tries to use a file with the list of dynamic symbols that need to be exported
7247330f729Sjoerg // from the runtime library. Returns true if the file was found.
addSanitizerDynamicList(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer)7257330f729Sjoerg static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
7267330f729Sjoerg                                     ArgStringList &CmdArgs,
7277330f729Sjoerg                                     StringRef Sanitizer) {
7287330f729Sjoerg   // Solaris ld defaults to --export-dynamic behaviour but doesn't support
7297330f729Sjoerg   // the option, so don't try to pass it.
7307330f729Sjoerg   if (TC.getTriple().getOS() == llvm::Triple::Solaris)
7317330f729Sjoerg     return true;
7327330f729Sjoerg   // Myriad is static linking only.  Furthermore, some versions of its
7337330f729Sjoerg   // linker have the bug where --export-dynamic overrides -static, so
7347330f729Sjoerg   // don't use --export-dynamic on that platform.
7357330f729Sjoerg   if (TC.getTriple().getVendor() == llvm::Triple::Myriad)
7367330f729Sjoerg     return true;
7377330f729Sjoerg   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
7387330f729Sjoerg   if (llvm::sys::fs::exists(SanRT + ".syms")) {
7397330f729Sjoerg     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
7407330f729Sjoerg     return true;
7417330f729Sjoerg   }
7427330f729Sjoerg   return false;
7437330f729Sjoerg }
7447330f729Sjoerg 
getAsNeededOption(const ToolChain & TC,bool as_needed)745*e038c9c4Sjoerg static const char *getAsNeededOption(const ToolChain &TC, bool as_needed) {
746*e038c9c4Sjoerg   // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
747*e038c9c4Sjoerg   // for the native forms -z ignore/-z record, they are missing in Illumos,
748*e038c9c4Sjoerg   // so always use the native form.
749*e038c9c4Sjoerg   if (TC.getTriple().isOSSolaris())
750*e038c9c4Sjoerg     return as_needed ? "-zignore" : "-zrecord";
751*e038c9c4Sjoerg   else
752*e038c9c4Sjoerg     return as_needed ? "--as-needed" : "--no-as-needed";
753*e038c9c4Sjoerg }
754*e038c9c4Sjoerg 
linkSanitizerRuntimeDeps(const ToolChain & TC,ArgStringList & CmdArgs)7557330f729Sjoerg void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
7567330f729Sjoerg                                      ArgStringList &CmdArgs) {
757*e038c9c4Sjoerg   // Fuchsia never needs these.  Any sanitizer runtimes with system
758*e038c9c4Sjoerg   // dependencies use the `.deplibs` feature instead.
759*e038c9c4Sjoerg   if (TC.getTriple().isOSFuchsia())
760*e038c9c4Sjoerg     return;
761*e038c9c4Sjoerg 
7627330f729Sjoerg   // Force linking against the system libraries sanitizers depends on
7637330f729Sjoerg   // (see PR15823 why this is necessary).
764*e038c9c4Sjoerg   CmdArgs.push_back(getAsNeededOption(TC, false));
7657330f729Sjoerg   // There's no libpthread or librt on RTEMS & Android.
7667330f729Sjoerg   if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
7677330f729Sjoerg       !TC.getTriple().isAndroid()) {
7687330f729Sjoerg     CmdArgs.push_back("-lpthread");
7697330f729Sjoerg     if (!TC.getTriple().isOSOpenBSD())
7707330f729Sjoerg       CmdArgs.push_back("-lrt");
7717330f729Sjoerg   }
7727330f729Sjoerg   CmdArgs.push_back("-lm");
7737330f729Sjoerg   // There's no libdl on all OSes.
7747330f729Sjoerg   if (!TC.getTriple().isOSFreeBSD() &&
7757330f729Sjoerg       !TC.getTriple().isOSNetBSD() &&
7767330f729Sjoerg       !TC.getTriple().isOSOpenBSD() &&
7777330f729Sjoerg        TC.getTriple().getOS() != llvm::Triple::RTEMS)
7787330f729Sjoerg     CmdArgs.push_back("-ldl");
7797330f729Sjoerg   // Required for backtrace on some OSes
7807330f729Sjoerg   if (TC.getTriple().isOSFreeBSD() ||
7817330f729Sjoerg       TC.getTriple().isOSNetBSD())
7827330f729Sjoerg     CmdArgs.push_back("-lexecinfo");
7837330f729Sjoerg }
7847330f729Sjoerg 
7857330f729Sjoerg static void
collectSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,SmallVectorImpl<StringRef> & SharedRuntimes,SmallVectorImpl<StringRef> & StaticRuntimes,SmallVectorImpl<StringRef> & NonWholeStaticRuntimes,SmallVectorImpl<StringRef> & HelperStaticRuntimes,SmallVectorImpl<StringRef> & RequiredSymbols)7867330f729Sjoerg collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
7877330f729Sjoerg                          SmallVectorImpl<StringRef> &SharedRuntimes,
7887330f729Sjoerg                          SmallVectorImpl<StringRef> &StaticRuntimes,
7897330f729Sjoerg                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
7907330f729Sjoerg                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
7917330f729Sjoerg                          SmallVectorImpl<StringRef> &RequiredSymbols) {
7927330f729Sjoerg   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
7937330f729Sjoerg   // Collect shared runtimes.
7947330f729Sjoerg   if (SanArgs.needsSharedRt()) {
7957330f729Sjoerg     if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
7967330f729Sjoerg       SharedRuntimes.push_back("asan");
7977330f729Sjoerg       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
7987330f729Sjoerg         HelperStaticRuntimes.push_back("asan-preinit");
7997330f729Sjoerg     }
800*e038c9c4Sjoerg     if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) {
801*e038c9c4Sjoerg       SharedRuntimes.push_back("memprof");
802*e038c9c4Sjoerg       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
803*e038c9c4Sjoerg         HelperStaticRuntimes.push_back("memprof-preinit");
804*e038c9c4Sjoerg     }
8057330f729Sjoerg     if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
8067330f729Sjoerg       if (SanArgs.requiresMinimalRuntime())
8077330f729Sjoerg         SharedRuntimes.push_back("ubsan_minimal");
8087330f729Sjoerg       else
8097330f729Sjoerg         SharedRuntimes.push_back("ubsan_standalone");
8107330f729Sjoerg     }
8117330f729Sjoerg     if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
8127330f729Sjoerg       if (SanArgs.requiresMinimalRuntime())
8137330f729Sjoerg         SharedRuntimes.push_back("scudo_minimal");
8147330f729Sjoerg       else
8157330f729Sjoerg         SharedRuntimes.push_back("scudo");
8167330f729Sjoerg     }
817*e038c9c4Sjoerg     if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes())
818*e038c9c4Sjoerg       SharedRuntimes.push_back("tsan");
819*e038c9c4Sjoerg     if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
820*e038c9c4Sjoerg       if (SanArgs.needsHwasanAliasesRt())
821*e038c9c4Sjoerg         SharedRuntimes.push_back("hwasan_aliases");
822*e038c9c4Sjoerg       else
8237330f729Sjoerg         SharedRuntimes.push_back("hwasan");
8247330f729Sjoerg     }
825*e038c9c4Sjoerg   }
8267330f729Sjoerg 
8277330f729Sjoerg   // The stats_client library is also statically linked into DSOs.
8287330f729Sjoerg   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
8297330f729Sjoerg     StaticRuntimes.push_back("stats_client");
8307330f729Sjoerg 
8317330f729Sjoerg   // Collect static runtimes.
832*e038c9c4Sjoerg   if (Args.hasArg(options::OPT_shared)) {
833*e038c9c4Sjoerg     // Don't link static runtimes into DSOs.
8347330f729Sjoerg     return;
8357330f729Sjoerg   }
836*e038c9c4Sjoerg 
837*e038c9c4Sjoerg   // Each static runtime that has a DSO counterpart above is excluded below,
838*e038c9c4Sjoerg   // but runtimes that exist only as static are not affected by needsSharedRt.
839*e038c9c4Sjoerg 
840*e038c9c4Sjoerg   if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
8417330f729Sjoerg     StaticRuntimes.push_back("asan");
8427330f729Sjoerg     if (SanArgs.linkCXXRuntimes())
8437330f729Sjoerg       StaticRuntimes.push_back("asan_cxx");
8447330f729Sjoerg   }
8457330f729Sjoerg 
846*e038c9c4Sjoerg   if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt() &&
847*e038c9c4Sjoerg       SanArgs.linkRuntimes()) {
848*e038c9c4Sjoerg     StaticRuntimes.push_back("memprof");
849*e038c9c4Sjoerg     if (SanArgs.linkCXXRuntimes())
850*e038c9c4Sjoerg       StaticRuntimes.push_back("memprof_cxx");
851*e038c9c4Sjoerg   }
852*e038c9c4Sjoerg 
853*e038c9c4Sjoerg   if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
854*e038c9c4Sjoerg     if (SanArgs.needsHwasanAliasesRt()) {
855*e038c9c4Sjoerg       StaticRuntimes.push_back("hwasan_aliases");
856*e038c9c4Sjoerg       if (SanArgs.linkCXXRuntimes())
857*e038c9c4Sjoerg         StaticRuntimes.push_back("hwasan_aliases_cxx");
858*e038c9c4Sjoerg     } else {
8597330f729Sjoerg       StaticRuntimes.push_back("hwasan");
8607330f729Sjoerg       if (SanArgs.linkCXXRuntimes())
8617330f729Sjoerg         StaticRuntimes.push_back("hwasan_cxx");
8627330f729Sjoerg     }
863*e038c9c4Sjoerg   }
8647330f729Sjoerg   if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes())
8657330f729Sjoerg     StaticRuntimes.push_back("dfsan");
8667330f729Sjoerg   if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes())
8677330f729Sjoerg     StaticRuntimes.push_back("lsan");
8687330f729Sjoerg   if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) {
8697330f729Sjoerg     StaticRuntimes.push_back("msan");
8707330f729Sjoerg     if (SanArgs.linkCXXRuntimes())
8717330f729Sjoerg       StaticRuntimes.push_back("msan_cxx");
8727330f729Sjoerg   }
873*e038c9c4Sjoerg   if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt() &&
874*e038c9c4Sjoerg       SanArgs.linkRuntimes()) {
8757330f729Sjoerg     StaticRuntimes.push_back("tsan");
8767330f729Sjoerg     if (SanArgs.linkCXXRuntimes())
8777330f729Sjoerg       StaticRuntimes.push_back("tsan_cxx");
8787330f729Sjoerg   }
879*e038c9c4Sjoerg   if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
8807330f729Sjoerg     if (SanArgs.requiresMinimalRuntime()) {
8817330f729Sjoerg       StaticRuntimes.push_back("ubsan_minimal");
8827330f729Sjoerg     } else {
8837330f729Sjoerg       StaticRuntimes.push_back("ubsan_standalone");
8847330f729Sjoerg       if (SanArgs.linkCXXRuntimes())
8857330f729Sjoerg         StaticRuntimes.push_back("ubsan_standalone_cxx");
8867330f729Sjoerg     }
8877330f729Sjoerg   }
8887330f729Sjoerg   if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) {
8897330f729Sjoerg     NonWholeStaticRuntimes.push_back("safestack");
8907330f729Sjoerg     RequiredSymbols.push_back("__safestack_init");
8917330f729Sjoerg   }
892*e038c9c4Sjoerg   if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) {
8937330f729Sjoerg     if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
8947330f729Sjoerg       StaticRuntimes.push_back("cfi");
8957330f729Sjoerg     if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) {
8967330f729Sjoerg       StaticRuntimes.push_back("cfi_diag");
8977330f729Sjoerg       if (SanArgs.linkCXXRuntimes())
8987330f729Sjoerg         StaticRuntimes.push_back("ubsan_standalone_cxx");
8997330f729Sjoerg     }
900*e038c9c4Sjoerg   }
9017330f729Sjoerg   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) {
9027330f729Sjoerg     NonWholeStaticRuntimes.push_back("stats");
9037330f729Sjoerg     RequiredSymbols.push_back("__sanitizer_stats_register");
9047330f729Sjoerg   }
905*e038c9c4Sjoerg   if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
9067330f729Sjoerg     if (SanArgs.requiresMinimalRuntime()) {
9077330f729Sjoerg       StaticRuntimes.push_back("scudo_minimal");
9087330f729Sjoerg       if (SanArgs.linkCXXRuntimes())
9097330f729Sjoerg         StaticRuntimes.push_back("scudo_cxx_minimal");
9107330f729Sjoerg     } else {
9117330f729Sjoerg       StaticRuntimes.push_back("scudo");
9127330f729Sjoerg       if (SanArgs.linkCXXRuntimes())
9137330f729Sjoerg         StaticRuntimes.push_back("scudo_cxx");
9147330f729Sjoerg     }
9157330f729Sjoerg   }
9167330f729Sjoerg }
9177330f729Sjoerg 
9187330f729Sjoerg // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
9197330f729Sjoerg // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
addSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)9207330f729Sjoerg bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
9217330f729Sjoerg                                  ArgStringList &CmdArgs) {
9227330f729Sjoerg   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
9237330f729Sjoerg       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
9247330f729Sjoerg   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
9257330f729Sjoerg                            NonWholeStaticRuntimes, HelperStaticRuntimes,
9267330f729Sjoerg                            RequiredSymbols);
9277330f729Sjoerg 
9287330f729Sjoerg   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
9297330f729Sjoerg   // Inject libfuzzer dependencies.
9307330f729Sjoerg   if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
9317330f729Sjoerg       !Args.hasArg(options::OPT_shared)) {
9327330f729Sjoerg 
9337330f729Sjoerg     addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
934*e038c9c4Sjoerg     if (SanArgs.needsFuzzerInterceptors())
935*e038c9c4Sjoerg       addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
936*e038c9c4Sjoerg                           true);
937*e038c9c4Sjoerg     if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
938*e038c9c4Sjoerg       bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
939*e038c9c4Sjoerg                                  !Args.hasArg(options::OPT_static);
940*e038c9c4Sjoerg       if (OnlyLibstdcxxStatic)
941*e038c9c4Sjoerg         CmdArgs.push_back("-Bstatic");
9427330f729Sjoerg       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
943*e038c9c4Sjoerg       if (OnlyLibstdcxxStatic)
944*e038c9c4Sjoerg         CmdArgs.push_back("-Bdynamic");
945*e038c9c4Sjoerg     }
9467330f729Sjoerg   }
9477330f729Sjoerg 
9487330f729Sjoerg   for (auto RT : SharedRuntimes)
9497330f729Sjoerg     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
9507330f729Sjoerg   for (auto RT : HelperStaticRuntimes)
9517330f729Sjoerg     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
9527330f729Sjoerg   bool AddExportDynamic = false;
9537330f729Sjoerg   for (auto RT : StaticRuntimes) {
9547330f729Sjoerg     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
9557330f729Sjoerg     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
9567330f729Sjoerg   }
9577330f729Sjoerg   for (auto RT : NonWholeStaticRuntimes) {
9587330f729Sjoerg     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
9597330f729Sjoerg     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
9607330f729Sjoerg   }
9617330f729Sjoerg   for (auto S : RequiredSymbols) {
9627330f729Sjoerg     CmdArgs.push_back("-u");
9637330f729Sjoerg     CmdArgs.push_back(Args.MakeArgString(S));
9647330f729Sjoerg   }
9657330f729Sjoerg   // If there is a static runtime with no dynamic list, force all the symbols
9667330f729Sjoerg   // to be dynamic to be sure we export sanitizer interface functions.
9677330f729Sjoerg   if (AddExportDynamic)
9687330f729Sjoerg     CmdArgs.push_back("--export-dynamic");
9697330f729Sjoerg 
9707330f729Sjoerg   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
971*e038c9c4Sjoerg     CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
9727330f729Sjoerg 
9737330f729Sjoerg   return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
9747330f729Sjoerg }
9757330f729Sjoerg 
addXRayRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)9767330f729Sjoerg bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
9777330f729Sjoerg   if (Args.hasArg(options::OPT_shared))
9787330f729Sjoerg     return false;
9797330f729Sjoerg 
9807330f729Sjoerg   if (TC.getXRayArgs().needsXRayRt()) {
9817330f729Sjoerg     CmdArgs.push_back("-whole-archive");
9827330f729Sjoerg     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
9837330f729Sjoerg     for (const auto &Mode : TC.getXRayArgs().modeList())
9847330f729Sjoerg       CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
9857330f729Sjoerg     CmdArgs.push_back("-no-whole-archive");
9867330f729Sjoerg     return true;
9877330f729Sjoerg   }
9887330f729Sjoerg 
9897330f729Sjoerg   return false;
9907330f729Sjoerg }
9917330f729Sjoerg 
linkXRayRuntimeDeps(const ToolChain & TC,ArgStringList & CmdArgs)9927330f729Sjoerg void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
993*e038c9c4Sjoerg   CmdArgs.push_back(getAsNeededOption(TC, false));
9947330f729Sjoerg   CmdArgs.push_back("-lpthread");
9957330f729Sjoerg   if (!TC.getTriple().isOSOpenBSD())
9967330f729Sjoerg     CmdArgs.push_back("-lrt");
9977330f729Sjoerg   CmdArgs.push_back("-lm");
9987330f729Sjoerg 
9997330f729Sjoerg   if (!TC.getTriple().isOSFreeBSD() &&
10007330f729Sjoerg       !TC.getTriple().isOSNetBSD() &&
10017330f729Sjoerg       !TC.getTriple().isOSOpenBSD())
10027330f729Sjoerg     CmdArgs.push_back("-ldl");
10037330f729Sjoerg }
10047330f729Sjoerg 
areOptimizationsEnabled(const ArgList & Args)10057330f729Sjoerg bool tools::areOptimizationsEnabled(const ArgList &Args) {
10067330f729Sjoerg   // Find the last -O arg and see if it is non-zero.
10077330f729Sjoerg   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
10087330f729Sjoerg     return !A->getOption().matches(options::OPT_O0);
10097330f729Sjoerg   // Defaults to -O0.
10107330f729Sjoerg   return false;
10117330f729Sjoerg }
10127330f729Sjoerg 
SplitDebugName(const JobAction & JA,const ArgList & Args,const InputInfo & Input,const InputInfo & Output)1013*e038c9c4Sjoerg const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
1014*e038c9c4Sjoerg                                   const InputInfo &Input,
10157330f729Sjoerg                                   const InputInfo &Output) {
1016*e038c9c4Sjoerg   auto AddPostfix = [JA](auto &F) {
1017*e038c9c4Sjoerg     if (JA.getOffloadingDeviceKind() == Action::OFK_HIP)
1018*e038c9c4Sjoerg       F += (Twine("_") + JA.getOffloadingArch()).str();
1019*e038c9c4Sjoerg     F += ".dwo";
1020*e038c9c4Sjoerg   };
10217330f729Sjoerg   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
10227330f729Sjoerg     if (StringRef(A->getValue()) == "single")
10237330f729Sjoerg       return Args.MakeArgString(Output.getFilename());
10247330f729Sjoerg 
10257330f729Sjoerg   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
10267330f729Sjoerg   if (FinalOutput && Args.hasArg(options::OPT_c)) {
10277330f729Sjoerg     SmallString<128> T(FinalOutput->getValue());
1028*e038c9c4Sjoerg     llvm::sys::path::remove_filename(T);
1029*e038c9c4Sjoerg     llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue()));
1030*e038c9c4Sjoerg     AddPostfix(T);
10317330f729Sjoerg     return Args.MakeArgString(T);
10327330f729Sjoerg   } else {
10337330f729Sjoerg     // Use the compilation dir.
1034*e038c9c4Sjoerg     Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
1035*e038c9c4Sjoerg                              options::OPT_fdebug_compilation_dir_EQ);
1036*e038c9c4Sjoerg     SmallString<128> T(A ? A->getValue() : "");
10377330f729Sjoerg     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
1038*e038c9c4Sjoerg     AddPostfix(F);
10397330f729Sjoerg     T += F;
1040*e038c9c4Sjoerg     return Args.MakeArgString(T);
10417330f729Sjoerg   }
10427330f729Sjoerg }
10437330f729Sjoerg 
SplitDebugInfo(const ToolChain & TC,Compilation & C,const Tool & T,const JobAction & JA,const ArgList & Args,const InputInfo & Output,const char * OutFile)10447330f729Sjoerg void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
10457330f729Sjoerg                            const JobAction &JA, const ArgList &Args,
10467330f729Sjoerg                            const InputInfo &Output, const char *OutFile) {
10477330f729Sjoerg   ArgStringList ExtractArgs;
10487330f729Sjoerg   ExtractArgs.push_back("--extract-dwo");
10497330f729Sjoerg 
10507330f729Sjoerg   ArgStringList StripArgs;
10517330f729Sjoerg   StripArgs.push_back("--strip-dwo");
10527330f729Sjoerg 
10537330f729Sjoerg   // Grabbing the output of the earlier compile step.
10547330f729Sjoerg   StripArgs.push_back(Output.getFilename());
10557330f729Sjoerg   ExtractArgs.push_back(Output.getFilename());
10567330f729Sjoerg   ExtractArgs.push_back(OutFile);
10577330f729Sjoerg 
10587330f729Sjoerg   const char *Exec =
10597330f729Sjoerg       Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
10607330f729Sjoerg   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
10617330f729Sjoerg 
10627330f729Sjoerg   // First extract the dwo sections.
1063*e038c9c4Sjoerg   C.addCommand(std::make_unique<Command>(JA, T,
1064*e038c9c4Sjoerg                                          ResponseFileSupport::AtFileCurCP(),
1065*e038c9c4Sjoerg                                          Exec, ExtractArgs, II, Output));
10667330f729Sjoerg 
10677330f729Sjoerg   // Then remove them from the original .o file.
1068*e038c9c4Sjoerg   C.addCommand(std::make_unique<Command>(
1069*e038c9c4Sjoerg       JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
10707330f729Sjoerg }
10717330f729Sjoerg 
10727330f729Sjoerg // Claim options we don't want to warn if they are unused. We do this for
10737330f729Sjoerg // options that build systems might add but are unused when assembling or only
10747330f729Sjoerg // running the preprocessor for example.
claimNoWarnArgs(const ArgList & Args)10757330f729Sjoerg void tools::claimNoWarnArgs(const ArgList &Args) {
10767330f729Sjoerg   // Don't warn about unused -f(no-)?lto.  This can happen when we're
10777330f729Sjoerg   // preprocessing, precompiling or assembling.
10787330f729Sjoerg   Args.ClaimAllArgs(options::OPT_flto_EQ);
10797330f729Sjoerg   Args.ClaimAllArgs(options::OPT_flto);
10807330f729Sjoerg   Args.ClaimAllArgs(options::OPT_fno_lto);
10817330f729Sjoerg }
10827330f729Sjoerg 
getLastProfileUseArg(const ArgList & Args)10837330f729Sjoerg Arg *tools::getLastProfileUseArg(const ArgList &Args) {
10847330f729Sjoerg   auto *ProfileUseArg = Args.getLastArg(
10857330f729Sjoerg       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
10867330f729Sjoerg       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
10877330f729Sjoerg       options::OPT_fno_profile_instr_use);
10887330f729Sjoerg 
10897330f729Sjoerg   if (ProfileUseArg &&
10907330f729Sjoerg       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
10917330f729Sjoerg     ProfileUseArg = nullptr;
10927330f729Sjoerg 
10937330f729Sjoerg   return ProfileUseArg;
10947330f729Sjoerg }
10957330f729Sjoerg 
getLastProfileSampleUseArg(const ArgList & Args)10967330f729Sjoerg Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
10977330f729Sjoerg   auto *ProfileSampleUseArg = Args.getLastArg(
10987330f729Sjoerg       options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
10997330f729Sjoerg       options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
11007330f729Sjoerg       options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
11017330f729Sjoerg 
11027330f729Sjoerg   if (ProfileSampleUseArg &&
11037330f729Sjoerg       (ProfileSampleUseArg->getOption().matches(
11047330f729Sjoerg            options::OPT_fno_profile_sample_use) ||
11057330f729Sjoerg        ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
11067330f729Sjoerg     return nullptr;
11077330f729Sjoerg 
11087330f729Sjoerg   return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
11097330f729Sjoerg                          options::OPT_fauto_profile_EQ);
11107330f729Sjoerg }
11117330f729Sjoerg 
11127330f729Sjoerg /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
11137330f729Sjoerg /// smooshes them together with platform defaults, to decide whether
11147330f729Sjoerg /// this compile should be using PIC mode or not. Returns a tuple of
11157330f729Sjoerg /// (RelocationModel, PICLevel, IsPIE).
11167330f729Sjoerg std::tuple<llvm::Reloc::Model, unsigned, bool>
ParsePICArgs(const ToolChain & ToolChain,const ArgList & Args)11177330f729Sjoerg tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
11187330f729Sjoerg   const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
11197330f729Sjoerg   const llvm::Triple &Triple = ToolChain.getTriple();
11207330f729Sjoerg 
11217330f729Sjoerg   bool PIE = ToolChain.isPIEDefault();
11227330f729Sjoerg   bool PIC = PIE || ToolChain.isPICDefault();
11237330f729Sjoerg   // The Darwin/MachO default to use PIC does not apply when using -static.
11247330f729Sjoerg   if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
11257330f729Sjoerg     PIE = PIC = false;
11267330f729Sjoerg   bool IsPICLevelTwo = PIC;
11277330f729Sjoerg 
11287330f729Sjoerg   bool KernelOrKext =
11297330f729Sjoerg       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
11307330f729Sjoerg 
11317330f729Sjoerg   // Android-specific defaults for PIC/PIE
11327330f729Sjoerg   if (Triple.isAndroid()) {
11337330f729Sjoerg     switch (Triple.getArch()) {
11347330f729Sjoerg     case llvm::Triple::arm:
11357330f729Sjoerg     case llvm::Triple::armeb:
11367330f729Sjoerg     case llvm::Triple::thumb:
11377330f729Sjoerg     case llvm::Triple::thumbeb:
11387330f729Sjoerg     case llvm::Triple::aarch64:
11397330f729Sjoerg     case llvm::Triple::mips:
11407330f729Sjoerg     case llvm::Triple::mipsel:
11417330f729Sjoerg     case llvm::Triple::mips64:
11427330f729Sjoerg     case llvm::Triple::mips64el:
11437330f729Sjoerg       PIC = true; // "-fpic"
11447330f729Sjoerg       break;
11457330f729Sjoerg 
11467330f729Sjoerg     case llvm::Triple::x86:
11477330f729Sjoerg     case llvm::Triple::x86_64:
11487330f729Sjoerg       PIC = true; // "-fPIC"
11497330f729Sjoerg       IsPICLevelTwo = true;
11507330f729Sjoerg       break;
11517330f729Sjoerg 
11527330f729Sjoerg     default:
11537330f729Sjoerg       break;
11547330f729Sjoerg     }
11557330f729Sjoerg   }
11567330f729Sjoerg 
11577330f729Sjoerg   // OpenBSD-specific defaults for PIE
11587330f729Sjoerg   if (Triple.isOSOpenBSD()) {
11597330f729Sjoerg     switch (ToolChain.getArch()) {
11607330f729Sjoerg     case llvm::Triple::arm:
11617330f729Sjoerg     case llvm::Triple::aarch64:
11627330f729Sjoerg     case llvm::Triple::mips64:
11637330f729Sjoerg     case llvm::Triple::mips64el:
11647330f729Sjoerg     case llvm::Triple::x86:
11657330f729Sjoerg     case llvm::Triple::x86_64:
11667330f729Sjoerg       IsPICLevelTwo = false; // "-fpie"
11677330f729Sjoerg       break;
11687330f729Sjoerg 
11697330f729Sjoerg     case llvm::Triple::ppc:
11707330f729Sjoerg     case llvm::Triple::sparcv9:
11717330f729Sjoerg       IsPICLevelTwo = true; // "-fPIE"
11727330f729Sjoerg       break;
11737330f729Sjoerg 
11747330f729Sjoerg     default:
11757330f729Sjoerg       break;
11767330f729Sjoerg     }
11777330f729Sjoerg   }
11787330f729Sjoerg 
11797330f729Sjoerg   // AMDGPU-specific defaults for PIC.
11807330f729Sjoerg   if (Triple.getArch() == llvm::Triple::amdgcn)
11817330f729Sjoerg     PIC = true;
11827330f729Sjoerg 
11837330f729Sjoerg   // The last argument relating to either PIC or PIE wins, and no
11847330f729Sjoerg   // other argument is used. If the last argument is any flavor of the
11857330f729Sjoerg   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
11867330f729Sjoerg   // option implicitly enables PIC at the same level.
11877330f729Sjoerg   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
11887330f729Sjoerg                                     options::OPT_fpic, options::OPT_fno_pic,
11897330f729Sjoerg                                     options::OPT_fPIE, options::OPT_fno_PIE,
11907330f729Sjoerg                                     options::OPT_fpie, options::OPT_fno_pie);
11917330f729Sjoerg   if (Triple.isOSWindows() && LastPICArg &&
11927330f729Sjoerg       LastPICArg ==
11937330f729Sjoerg           Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
11947330f729Sjoerg                           options::OPT_fPIE, options::OPT_fpie)) {
11957330f729Sjoerg     ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
11967330f729Sjoerg         << LastPICArg->getSpelling() << Triple.str();
11977330f729Sjoerg     if (Triple.getArch() == llvm::Triple::x86_64)
11987330f729Sjoerg       return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
11997330f729Sjoerg     return std::make_tuple(llvm::Reloc::Static, 0U, false);
12007330f729Sjoerg   }
12017330f729Sjoerg 
12027330f729Sjoerg   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
12037330f729Sjoerg   // is forced, then neither PIC nor PIE flags will have no effect.
12047330f729Sjoerg   if (!ToolChain.isPICDefaultForced()) {
12057330f729Sjoerg     if (LastPICArg) {
12067330f729Sjoerg       Option O = LastPICArg->getOption();
12077330f729Sjoerg       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
12087330f729Sjoerg           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
12097330f729Sjoerg         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
12107330f729Sjoerg         PIC =
12117330f729Sjoerg             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
12127330f729Sjoerg         IsPICLevelTwo =
12137330f729Sjoerg             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
12147330f729Sjoerg       } else {
12157330f729Sjoerg         PIE = PIC = false;
12167330f729Sjoerg         if (EffectiveTriple.isPS4CPU()) {
12177330f729Sjoerg           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
12187330f729Sjoerg           StringRef Model = ModelArg ? ModelArg->getValue() : "";
12197330f729Sjoerg           if (Model != "kernel") {
12207330f729Sjoerg             PIC = true;
12217330f729Sjoerg             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
12227330f729Sjoerg                 << LastPICArg->getSpelling();
12237330f729Sjoerg           }
12247330f729Sjoerg         }
12257330f729Sjoerg       }
12267330f729Sjoerg     }
12277330f729Sjoerg   }
12287330f729Sjoerg 
12297330f729Sjoerg   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
12307330f729Sjoerg   // PIC level would've been set to level 1, force it back to level 2 PIC
12317330f729Sjoerg   // instead.
12327330f729Sjoerg   if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
12337330f729Sjoerg     IsPICLevelTwo |= ToolChain.isPICDefault();
12347330f729Sjoerg 
12357330f729Sjoerg   // This kernel flags are a trump-card: they will disable PIC/PIE
12367330f729Sjoerg   // generation, independent of the argument order.
12377330f729Sjoerg   if (KernelOrKext &&
12387330f729Sjoerg       ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
12397330f729Sjoerg        !EffectiveTriple.isWatchOS()))
12407330f729Sjoerg     PIC = PIE = false;
12417330f729Sjoerg 
12427330f729Sjoerg   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
12437330f729Sjoerg     // This is a very special mode. It trumps the other modes, almost no one
12447330f729Sjoerg     // uses it, and it isn't even valid on any OS but Darwin.
12457330f729Sjoerg     if (!Triple.isOSDarwin())
12467330f729Sjoerg       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
12477330f729Sjoerg           << A->getSpelling() << Triple.str();
12487330f729Sjoerg 
12497330f729Sjoerg     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
12507330f729Sjoerg 
12517330f729Sjoerg     // Only a forced PIC mode can cause the actual compile to have PIC defines
12527330f729Sjoerg     // etc., no flags are sufficient. This behavior was selected to closely
12537330f729Sjoerg     // match that of llvm-gcc and Apple GCC before that.
12547330f729Sjoerg     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
12557330f729Sjoerg 
12567330f729Sjoerg     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
12577330f729Sjoerg   }
12587330f729Sjoerg 
12597330f729Sjoerg   bool EmbeddedPISupported;
12607330f729Sjoerg   switch (Triple.getArch()) {
12617330f729Sjoerg     case llvm::Triple::arm:
12627330f729Sjoerg     case llvm::Triple::armeb:
12637330f729Sjoerg     case llvm::Triple::thumb:
12647330f729Sjoerg     case llvm::Triple::thumbeb:
12657330f729Sjoerg       EmbeddedPISupported = true;
12667330f729Sjoerg       break;
12677330f729Sjoerg     default:
12687330f729Sjoerg       EmbeddedPISupported = false;
12697330f729Sjoerg       break;
12707330f729Sjoerg   }
12717330f729Sjoerg 
12727330f729Sjoerg   bool ROPI = false, RWPI = false;
12737330f729Sjoerg   Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
12747330f729Sjoerg   if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
12757330f729Sjoerg     if (!EmbeddedPISupported)
12767330f729Sjoerg       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
12777330f729Sjoerg           << LastROPIArg->getSpelling() << Triple.str();
12787330f729Sjoerg     ROPI = true;
12797330f729Sjoerg   }
12807330f729Sjoerg   Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
12817330f729Sjoerg   if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
12827330f729Sjoerg     if (!EmbeddedPISupported)
12837330f729Sjoerg       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
12847330f729Sjoerg           << LastRWPIArg->getSpelling() << Triple.str();
12857330f729Sjoerg     RWPI = true;
12867330f729Sjoerg   }
12877330f729Sjoerg 
12887330f729Sjoerg   // ROPI and RWPI are not compatible with PIC or PIE.
12897330f729Sjoerg   if ((ROPI || RWPI) && (PIC || PIE))
12907330f729Sjoerg     ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
12917330f729Sjoerg 
12927330f729Sjoerg   if (Triple.isMIPS()) {
12937330f729Sjoerg     StringRef CPUName;
12947330f729Sjoerg     StringRef ABIName;
12957330f729Sjoerg     mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
12967330f729Sjoerg     // When targeting the N64 ABI, PIC is the default, except in the case
12977330f729Sjoerg     // when the -mno-abicalls option is used. In that case we exit
12987330f729Sjoerg     // at next check regardless of PIC being set below.
12997330f729Sjoerg     if (ABIName == "n64")
13007330f729Sjoerg       PIC = true;
13017330f729Sjoerg     // When targettng MIPS with -mno-abicalls, it's always static.
13027330f729Sjoerg     if(Args.hasArg(options::OPT_mno_abicalls))
13037330f729Sjoerg       return std::make_tuple(llvm::Reloc::Static, 0U, false);
13047330f729Sjoerg     // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
13057330f729Sjoerg     // does not use PIC level 2 for historical reasons.
13067330f729Sjoerg     IsPICLevelTwo = false;
13077330f729Sjoerg   }
13087330f729Sjoerg 
13097330f729Sjoerg   if (PIC)
13107330f729Sjoerg     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
13117330f729Sjoerg 
13127330f729Sjoerg   llvm::Reloc::Model RelocM = llvm::Reloc::Static;
13137330f729Sjoerg   if (ROPI && RWPI)
13147330f729Sjoerg     RelocM = llvm::Reloc::ROPI_RWPI;
13157330f729Sjoerg   else if (ROPI)
13167330f729Sjoerg     RelocM = llvm::Reloc::ROPI;
13177330f729Sjoerg   else if (RWPI)
13187330f729Sjoerg     RelocM = llvm::Reloc::RWPI;
13197330f729Sjoerg 
13207330f729Sjoerg   return std::make_tuple(RelocM, 0U, false);
13217330f729Sjoerg }
13227330f729Sjoerg 
13237330f729Sjoerg // `-falign-functions` indicates that the functions should be aligned to a
13247330f729Sjoerg // 16-byte boundary.
13257330f729Sjoerg //
13267330f729Sjoerg // `-falign-functions=1` is the same as `-fno-align-functions`.
13277330f729Sjoerg //
13287330f729Sjoerg // The scalar `n` in `-falign-functions=n` must be an integral value between
13297330f729Sjoerg // [0, 65536].  If the value is not a power-of-two, it will be rounded up to
13307330f729Sjoerg // the nearest power-of-two.
13317330f729Sjoerg //
13327330f729Sjoerg // If we return `0`, the frontend will default to the backend's preferred
13337330f729Sjoerg // alignment.
13347330f729Sjoerg //
13357330f729Sjoerg // NOTE: icc only allows values between [0, 4096].  icc uses `-falign-functions`
13367330f729Sjoerg // to mean `-falign-functions=16`.  GCC defaults to the backend's preferred
13377330f729Sjoerg // alignment.  For unaligned functions, we default to the backend's preferred
13387330f729Sjoerg // alignment.
ParseFunctionAlignment(const ToolChain & TC,const ArgList & Args)13397330f729Sjoerg unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
13407330f729Sjoerg                                        const ArgList &Args) {
13417330f729Sjoerg   const Arg *A = Args.getLastArg(options::OPT_falign_functions,
13427330f729Sjoerg                                  options::OPT_falign_functions_EQ,
13437330f729Sjoerg                                  options::OPT_fno_align_functions);
13447330f729Sjoerg   if (!A || A->getOption().matches(options::OPT_fno_align_functions))
13457330f729Sjoerg     return 0;
13467330f729Sjoerg 
13477330f729Sjoerg   if (A->getOption().matches(options::OPT_falign_functions))
13487330f729Sjoerg     return 0;
13497330f729Sjoerg 
13507330f729Sjoerg   unsigned Value = 0;
13517330f729Sjoerg   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
13527330f729Sjoerg     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
13537330f729Sjoerg         << A->getAsString(Args) << A->getValue();
13547330f729Sjoerg   return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
13557330f729Sjoerg }
13567330f729Sjoerg 
ParseDebugDefaultVersion(const ToolChain & TC,const ArgList & Args)1357*e038c9c4Sjoerg unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC,
1358*e038c9c4Sjoerg                                          const ArgList &Args) {
1359*e038c9c4Sjoerg   const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
1360*e038c9c4Sjoerg 
1361*e038c9c4Sjoerg   if (!A)
1362*e038c9c4Sjoerg     return 0;
1363*e038c9c4Sjoerg 
1364*e038c9c4Sjoerg   unsigned Value = 0;
1365*e038c9c4Sjoerg   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
1366*e038c9c4Sjoerg       Value < 2)
1367*e038c9c4Sjoerg     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1368*e038c9c4Sjoerg         << A->getAsString(Args) << A->getValue();
1369*e038c9c4Sjoerg   return Value;
1370*e038c9c4Sjoerg }
1371*e038c9c4Sjoerg 
AddAssemblerKPIC(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs)13727330f729Sjoerg void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
13737330f729Sjoerg                              ArgStringList &CmdArgs) {
13747330f729Sjoerg   llvm::Reloc::Model RelocationModel;
13757330f729Sjoerg   unsigned PICLevel;
13767330f729Sjoerg   bool IsPIE;
13777330f729Sjoerg   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
13787330f729Sjoerg 
13797330f729Sjoerg   if (RelocationModel != llvm::Reloc::Static)
13807330f729Sjoerg     CmdArgs.push_back("-KPIC");
13817330f729Sjoerg }
13827330f729Sjoerg 
13837330f729Sjoerg /// Determine whether Objective-C automated reference counting is
13847330f729Sjoerg /// enabled.
isObjCAutoRefCount(const ArgList & Args)13857330f729Sjoerg bool tools::isObjCAutoRefCount(const ArgList &Args) {
13867330f729Sjoerg   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
13877330f729Sjoerg }
13887330f729Sjoerg 
13897330f729Sjoerg enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
13907330f729Sjoerg 
getLibGccType(const ToolChain & TC,const Driver & D,const ArgList & Args)1391*e038c9c4Sjoerg static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
1392*e038c9c4Sjoerg                                 const ArgList &Args) {
13937330f729Sjoerg   if (Args.hasArg(options::OPT_static_libgcc) ||
13947330f729Sjoerg       Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie))
13957330f729Sjoerg     return LibGccType::StaticLibGcc;
1396*e038c9c4Sjoerg   if (Args.hasArg(options::OPT_shared_libgcc))
1397*e038c9c4Sjoerg     return LibGccType::SharedLibGcc;
1398*e038c9c4Sjoerg   // The Android NDK only provides libunwind.a, not libunwind.so.
1399*e038c9c4Sjoerg   if (TC.getTriple().isAndroid())
1400*e038c9c4Sjoerg     return LibGccType::StaticLibGcc;
1401*e038c9c4Sjoerg   // For MinGW, don't imply a shared libgcc here, we only want to return
1402*e038c9c4Sjoerg   // SharedLibGcc if that was explicitly requested.
1403*e038c9c4Sjoerg   if (D.CCCIsCXX() && !TC.getTriple().isOSCygMing())
14047330f729Sjoerg     return LibGccType::SharedLibGcc;
14057330f729Sjoerg   return LibGccType::UnspecifiedLibGcc;
14067330f729Sjoerg }
14077330f729Sjoerg 
14087330f729Sjoerg // Gcc adds libgcc arguments in various ways:
14097330f729Sjoerg //
14107330f729Sjoerg // gcc <none>:     -lgcc --as-needed -lgcc_s --no-as-needed
14117330f729Sjoerg // g++ <none>:                       -lgcc_s               -lgcc
14127330f729Sjoerg // gcc shared:                       -lgcc_s               -lgcc
14137330f729Sjoerg // g++ shared:                       -lgcc_s               -lgcc
14147330f729Sjoerg // gcc static:     -lgcc             -lgcc_eh
14157330f729Sjoerg // g++ static:     -lgcc             -lgcc_eh
14167330f729Sjoerg // gcc static-pie: -lgcc             -lgcc_eh
14177330f729Sjoerg // g++ static-pie: -lgcc             -lgcc_eh
14187330f729Sjoerg //
14197330f729Sjoerg // Also, certain targets need additional adjustments.
14207330f729Sjoerg 
AddUnwindLibrary(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)14217330f729Sjoerg static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
14227330f729Sjoerg                              ArgStringList &CmdArgs, const ArgList &Args) {
14237330f729Sjoerg   ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
14247330f729Sjoerg   // Targets that don't use unwind libraries.
1425*e038c9c4Sjoerg   if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
1426*e038c9c4Sjoerg       TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
14277330f729Sjoerg       UNW == ToolChain::UNW_None)
14287330f729Sjoerg     return;
14297330f729Sjoerg 
1430*e038c9c4Sjoerg   LibGccType LGT = getLibGccType(TC, D, Args);
14317330f729Sjoerg   bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
14327330f729Sjoerg                   !TC.getTriple().isAndroid() && !TC.getTriple().isOSCygMing();
14337330f729Sjoerg   if (AsNeeded)
1434*e038c9c4Sjoerg     CmdArgs.push_back(getAsNeededOption(TC, true));
14357330f729Sjoerg 
14367330f729Sjoerg   switch (UNW) {
14377330f729Sjoerg   case ToolChain::UNW_None:
14387330f729Sjoerg     return;
14397330f729Sjoerg   case ToolChain::UNW_Libgcc: {
14407330f729Sjoerg     if (LGT == LibGccType::StaticLibGcc)
14417330f729Sjoerg       CmdArgs.push_back("-lgcc_eh");
14427330f729Sjoerg     else
14437330f729Sjoerg       CmdArgs.push_back("-lgcc_s");
14447330f729Sjoerg     break;
14457330f729Sjoerg   }
14467330f729Sjoerg   case ToolChain::UNW_CompilerRT:
1447*e038c9c4Sjoerg     if (LGT == LibGccType::StaticLibGcc)
1448*e038c9c4Sjoerg       CmdArgs.push_back("-l:libunwind.a");
1449*e038c9c4Sjoerg     else if (TC.getTriple().isOSCygMing()) {
1450*e038c9c4Sjoerg       if (LGT == LibGccType::SharedLibGcc)
1451*e038c9c4Sjoerg         CmdArgs.push_back("-l:libunwind.dll.a");
1452*e038c9c4Sjoerg       else
1453*e038c9c4Sjoerg         // Let the linker choose between libunwind.dll.a and libunwind.a
1454*e038c9c4Sjoerg         // depending on what's available, and depending on the -static flag
14557330f729Sjoerg         CmdArgs.push_back("-lunwind");
1456*e038c9c4Sjoerg     } else
1457*e038c9c4Sjoerg       CmdArgs.push_back("-l:libunwind.so");
14587330f729Sjoerg     break;
14597330f729Sjoerg   }
14607330f729Sjoerg 
14617330f729Sjoerg   if (AsNeeded)
1462*e038c9c4Sjoerg     CmdArgs.push_back(getAsNeededOption(TC, false));
14637330f729Sjoerg }
14647330f729Sjoerg 
AddLibgcc(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)14657330f729Sjoerg static void AddLibgcc(const ToolChain &TC, const Driver &D,
14667330f729Sjoerg                       ArgStringList &CmdArgs, const ArgList &Args) {
1467*e038c9c4Sjoerg   LibGccType LGT = getLibGccType(TC, D, Args);
14687330f729Sjoerg   if (LGT != LibGccType::SharedLibGcc)
14697330f729Sjoerg     CmdArgs.push_back("-lgcc");
14707330f729Sjoerg   AddUnwindLibrary(TC, D, CmdArgs, Args);
14717330f729Sjoerg   if (LGT == LibGccType::SharedLibGcc)
14727330f729Sjoerg     CmdArgs.push_back("-lgcc");
14737330f729Sjoerg }
14747330f729Sjoerg 
AddRunTimeLibs(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)14757330f729Sjoerg void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
14767330f729Sjoerg                            ArgStringList &CmdArgs, const ArgList &Args) {
14777330f729Sjoerg   // Make use of compiler-rt if --rtlib option is used
14787330f729Sjoerg   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
14797330f729Sjoerg 
14807330f729Sjoerg   switch (RLT) {
14817330f729Sjoerg   case ToolChain::RLT_CompilerRT:
14827330f729Sjoerg     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
14837330f729Sjoerg     AddUnwindLibrary(TC, D, CmdArgs, Args);
14847330f729Sjoerg     break;
14857330f729Sjoerg   case ToolChain::RLT_Libgcc:
14867330f729Sjoerg     // Make sure libgcc is not used under MSVC environment by default
14877330f729Sjoerg     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
14887330f729Sjoerg       // Issue error diagnostic if libgcc is explicitly specified
14897330f729Sjoerg       // through command line as --rtlib option argument.
14907330f729Sjoerg       if (Args.hasArg(options::OPT_rtlib_EQ)) {
14917330f729Sjoerg         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
14927330f729Sjoerg             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
14937330f729Sjoerg       }
14947330f729Sjoerg     } else
14957330f729Sjoerg       AddLibgcc(TC, D, CmdArgs, Args);
14967330f729Sjoerg     break;
14977330f729Sjoerg   }
14987330f729Sjoerg 
1499*e038c9c4Sjoerg   // On Android, the unwinder uses dl_iterate_phdr (or one of
1500*e038c9c4Sjoerg   // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
1501*e038c9c4Sjoerg   // statically-linked executables, these functions come from libc.a instead.
1502*e038c9c4Sjoerg   if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) &&
1503*e038c9c4Sjoerg       !Args.hasArg(options::OPT_static_pie))
1504*e038c9c4Sjoerg     CmdArgs.push_back("-ldl");
15057330f729Sjoerg }
15067330f729Sjoerg 
getStatsFileName(const llvm::opt::ArgList & Args,const InputInfo & Output,const InputInfo & Input,const Driver & D)15077330f729Sjoerg SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
15087330f729Sjoerg                                          const InputInfo &Output,
15097330f729Sjoerg                                          const InputInfo &Input,
15107330f729Sjoerg                                          const Driver &D) {
15117330f729Sjoerg   const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
15127330f729Sjoerg   if (!A)
15137330f729Sjoerg     return {};
15147330f729Sjoerg 
15157330f729Sjoerg   StringRef SaveStats = A->getValue();
15167330f729Sjoerg   SmallString<128> StatsFile;
15177330f729Sjoerg   if (SaveStats == "obj" && Output.isFilename()) {
15187330f729Sjoerg     StatsFile.assign(Output.getFilename());
15197330f729Sjoerg     llvm::sys::path::remove_filename(StatsFile);
15207330f729Sjoerg   } else if (SaveStats != "cwd") {
15217330f729Sjoerg     D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
15227330f729Sjoerg     return {};
15237330f729Sjoerg   }
15247330f729Sjoerg 
15257330f729Sjoerg   StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
15267330f729Sjoerg   llvm::sys::path::append(StatsFile, BaseName);
15277330f729Sjoerg   llvm::sys::path::replace_extension(StatsFile, "stats");
15287330f729Sjoerg   return StatsFile;
15297330f729Sjoerg }
15307330f729Sjoerg 
addMultilibFlag(bool Enabled,const char * const Flag,Multilib::flags_list & Flags)15317330f729Sjoerg void tools::addMultilibFlag(bool Enabled, const char *const Flag,
15327330f729Sjoerg                             Multilib::flags_list &Flags) {
15337330f729Sjoerg   Flags.push_back(std::string(Enabled ? "+" : "-") + Flag);
15347330f729Sjoerg }
15357330f729Sjoerg 
addX86AlignBranchArgs(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,bool IsLTO)1536*e038c9c4Sjoerg void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
1537*e038c9c4Sjoerg                                   ArgStringList &CmdArgs, bool IsLTO) {
1538*e038c9c4Sjoerg   auto addArg = [&, IsLTO](const Twine &Arg) {
1539*e038c9c4Sjoerg     if (IsLTO) {
1540*e038c9c4Sjoerg       CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
15417330f729Sjoerg     } else {
1542*e038c9c4Sjoerg       CmdArgs.push_back("-mllvm");
1543*e038c9c4Sjoerg       CmdArgs.push_back(Args.MakeArgString(Arg));
1544*e038c9c4Sjoerg     }
1545*e038c9c4Sjoerg   };
1546*e038c9c4Sjoerg 
1547*e038c9c4Sjoerg   if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
1548*e038c9c4Sjoerg     addArg(Twine("-x86-branches-within-32B-boundaries"));
1549*e038c9c4Sjoerg   }
1550*e038c9c4Sjoerg   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
1551*e038c9c4Sjoerg     StringRef Value = A->getValue();
1552*e038c9c4Sjoerg     unsigned Boundary;
1553*e038c9c4Sjoerg     if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
1554*e038c9c4Sjoerg         !llvm::isPowerOf2_64(Boundary)) {
1555*e038c9c4Sjoerg       D.Diag(diag::err_drv_invalid_argument_to_option)
1556*e038c9c4Sjoerg           << Value << A->getOption().getName();
1557*e038c9c4Sjoerg     } else {
1558*e038c9c4Sjoerg       addArg("-x86-align-branch-boundary=" + Twine(Boundary));
1559*e038c9c4Sjoerg     }
1560*e038c9c4Sjoerg   }
1561*e038c9c4Sjoerg   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
1562*e038c9c4Sjoerg     std::string AlignBranch;
1563*e038c9c4Sjoerg     for (StringRef T : A->getValues()) {
1564*e038c9c4Sjoerg       if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
1565*e038c9c4Sjoerg           T != "ret" && T != "indirect")
1566*e038c9c4Sjoerg         D.Diag(diag::err_drv_invalid_malign_branch_EQ)
1567*e038c9c4Sjoerg             << T << "fused, jcc, jmp, call, ret, indirect";
1568*e038c9c4Sjoerg       if (!AlignBranch.empty())
1569*e038c9c4Sjoerg         AlignBranch += '+';
1570*e038c9c4Sjoerg       AlignBranch += T;
1571*e038c9c4Sjoerg     }
1572*e038c9c4Sjoerg     addArg("-x86-align-branch=" + Twine(AlignBranch));
1573*e038c9c4Sjoerg   }
1574*e038c9c4Sjoerg   if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
1575*e038c9c4Sjoerg     StringRef Value = A->getValue();
1576*e038c9c4Sjoerg     unsigned PrefixSize;
1577*e038c9c4Sjoerg     if (Value.getAsInteger(10, PrefixSize)) {
1578*e038c9c4Sjoerg       D.Diag(diag::err_drv_invalid_argument_to_option)
1579*e038c9c4Sjoerg           << Value << A->getOption().getName();
1580*e038c9c4Sjoerg     } else {
1581*e038c9c4Sjoerg       addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
15827330f729Sjoerg     }
15837330f729Sjoerg   }
15847330f729Sjoerg }
15857330f729Sjoerg 
1586*e038c9c4Sjoerg static llvm::opt::Arg *
getAMDGPUCodeObjectArgument(const Driver & D,const llvm::opt::ArgList & Args)1587*e038c9c4Sjoerg getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
1588*e038c9c4Sjoerg   // The last of -mcode-object-v3, -mno-code-object-v3 and
1589*e038c9c4Sjoerg   // -mcode-object-version=<version> wins.
1590*e038c9c4Sjoerg   return Args.getLastArg(options::OPT_mcode_object_v3_legacy,
1591*e038c9c4Sjoerg                          options::OPT_mno_code_object_v3_legacy,
1592*e038c9c4Sjoerg                          options::OPT_mcode_object_version_EQ);
1593*e038c9c4Sjoerg }
1594*e038c9c4Sjoerg 
checkAMDGPUCodeObjectVersion(const Driver & D,const llvm::opt::ArgList & Args)1595*e038c9c4Sjoerg void tools::checkAMDGPUCodeObjectVersion(const Driver &D,
1596*e038c9c4Sjoerg                                          const llvm::opt::ArgList &Args) {
1597*e038c9c4Sjoerg   const unsigned MinCodeObjVer = 2;
1598*e038c9c4Sjoerg   const unsigned MaxCodeObjVer = 4;
1599*e038c9c4Sjoerg 
1600*e038c9c4Sjoerg   // Emit warnings for legacy options even if they are overridden.
1601*e038c9c4Sjoerg   if (Args.hasArg(options::OPT_mno_code_object_v3_legacy))
1602*e038c9c4Sjoerg     D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3"
1603*e038c9c4Sjoerg                                           << "-mcode-object-version=2";
1604*e038c9c4Sjoerg 
1605*e038c9c4Sjoerg   if (Args.hasArg(options::OPT_mcode_object_v3_legacy))
1606*e038c9c4Sjoerg     D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3"
1607*e038c9c4Sjoerg                                           << "-mcode-object-version=3";
1608*e038c9c4Sjoerg 
1609*e038c9c4Sjoerg   if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
1610*e038c9c4Sjoerg     if (CodeObjArg->getOption().getID() ==
1611*e038c9c4Sjoerg         options::OPT_mcode_object_version_EQ) {
1612*e038c9c4Sjoerg       unsigned CodeObjVer = MaxCodeObjVer;
1613*e038c9c4Sjoerg       auto Remnant =
1614*e038c9c4Sjoerg           StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
1615*e038c9c4Sjoerg       if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)
1616*e038c9c4Sjoerg         D.Diag(diag::err_drv_invalid_int_value)
1617*e038c9c4Sjoerg             << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
1618*e038c9c4Sjoerg     }
1619*e038c9c4Sjoerg   }
1620*e038c9c4Sjoerg }
1621*e038c9c4Sjoerg 
getAMDGPUCodeObjectVersion(const Driver & D,const llvm::opt::ArgList & Args)1622*e038c9c4Sjoerg unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D,
1623*e038c9c4Sjoerg                                            const llvm::opt::ArgList &Args) {
1624*e038c9c4Sjoerg   unsigned CodeObjVer = 4; // default
1625*e038c9c4Sjoerg   if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
1626*e038c9c4Sjoerg     if (CodeObjArg->getOption().getID() ==
1627*e038c9c4Sjoerg         options::OPT_mno_code_object_v3_legacy) {
1628*e038c9c4Sjoerg       CodeObjVer = 2;
1629*e038c9c4Sjoerg     } else if (CodeObjArg->getOption().getID() ==
1630*e038c9c4Sjoerg                options::OPT_mcode_object_v3_legacy) {
1631*e038c9c4Sjoerg       CodeObjVer = 3;
1632*e038c9c4Sjoerg     } else {
1633*e038c9c4Sjoerg       StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
1634*e038c9c4Sjoerg     }
1635*e038c9c4Sjoerg   }
1636*e038c9c4Sjoerg   return CodeObjVer;
1637*e038c9c4Sjoerg }
1638*e038c9c4Sjoerg 
haveAMDGPUCodeObjectVersionArgument(const Driver & D,const llvm::opt::ArgList & Args)1639*e038c9c4Sjoerg bool tools::haveAMDGPUCodeObjectVersionArgument(
1640*e038c9c4Sjoerg     const Driver &D, const llvm::opt::ArgList &Args) {
1641*e038c9c4Sjoerg   return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
1642*e038c9c4Sjoerg }
1643*e038c9c4Sjoerg 
addMachineOutlinerArgs(const Driver & D,const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs,const llvm::Triple & Triple,bool IsLTO)1644*e038c9c4Sjoerg void tools::addMachineOutlinerArgs(const Driver &D,
1645*e038c9c4Sjoerg                                    const llvm::opt::ArgList &Args,
1646*e038c9c4Sjoerg                                    llvm::opt::ArgStringList &CmdArgs,
1647*e038c9c4Sjoerg                                    const llvm::Triple &Triple, bool IsLTO) {
1648*e038c9c4Sjoerg   auto addArg = [&, IsLTO](const Twine &Arg) {
1649*e038c9c4Sjoerg     if (IsLTO) {
1650*e038c9c4Sjoerg       CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
1651*e038c9c4Sjoerg     } else {
1652*e038c9c4Sjoerg       CmdArgs.push_back("-mllvm");
1653*e038c9c4Sjoerg       CmdArgs.push_back(Args.MakeArgString(Arg));
1654*e038c9c4Sjoerg     }
1655*e038c9c4Sjoerg   };
1656*e038c9c4Sjoerg 
1657*e038c9c4Sjoerg   if (Arg *A = Args.getLastArg(options::OPT_moutline,
1658*e038c9c4Sjoerg                                options::OPT_mno_outline)) {
1659*e038c9c4Sjoerg     if (A->getOption().matches(options::OPT_moutline)) {
1660*e038c9c4Sjoerg       // We only support -moutline in AArch64 and ARM targets right now. If
1661*e038c9c4Sjoerg       // we're not compiling for these, emit a warning and ignore the flag.
1662*e038c9c4Sjoerg       // Otherwise, add the proper mllvm flags.
1663*e038c9c4Sjoerg       if (!(Triple.isARM() || Triple.isThumb() ||
1664*e038c9c4Sjoerg             Triple.getArch() == llvm::Triple::aarch64 ||
1665*e038c9c4Sjoerg             Triple.getArch() == llvm::Triple::aarch64_32)) {
1666*e038c9c4Sjoerg         D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
1667*e038c9c4Sjoerg       } else {
1668*e038c9c4Sjoerg         addArg(Twine("-enable-machine-outliner"));
1669*e038c9c4Sjoerg       }
1670*e038c9c4Sjoerg     } else {
1671*e038c9c4Sjoerg       // Disable all outlining behaviour.
1672*e038c9c4Sjoerg       addArg(Twine("-enable-machine-outliner=never"));
1673*e038c9c4Sjoerg     }
1674*e038c9c4Sjoerg   }
1675*e038c9c4Sjoerg }
1676*e038c9c4Sjoerg 
addOpenMPDeviceRTL(const Driver & D,const llvm::opt::ArgList & DriverArgs,llvm::opt::ArgStringList & CC1Args,StringRef BitcodeSuffix,const llvm::Triple & Triple)1677*e038c9c4Sjoerg void tools::addOpenMPDeviceRTL(const Driver &D,
1678*e038c9c4Sjoerg                                const llvm::opt::ArgList &DriverArgs,
1679*e038c9c4Sjoerg                                llvm::opt::ArgStringList &CC1Args,
1680*e038c9c4Sjoerg                                StringRef BitcodeSuffix,
1681*e038c9c4Sjoerg                                const llvm::Triple &Triple) {
1682*e038c9c4Sjoerg   SmallVector<StringRef, 8> LibraryPaths;
1683*e038c9c4Sjoerg   // Add user defined library paths from LIBRARY_PATH.
1684*e038c9c4Sjoerg   llvm::Optional<std::string> LibPath =
1685*e038c9c4Sjoerg       llvm::sys::Process::GetEnv("LIBRARY_PATH");
1686*e038c9c4Sjoerg   if (LibPath) {
1687*e038c9c4Sjoerg     SmallVector<StringRef, 8> Frags;
1688*e038c9c4Sjoerg     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
1689*e038c9c4Sjoerg     llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
1690*e038c9c4Sjoerg     for (StringRef Path : Frags)
1691*e038c9c4Sjoerg       LibraryPaths.emplace_back(Path.trim());
1692*e038c9c4Sjoerg   }
1693*e038c9c4Sjoerg 
1694*e038c9c4Sjoerg   // Add path to lib / lib64 folder.
1695*e038c9c4Sjoerg   SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
1696*e038c9c4Sjoerg   llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
1697*e038c9c4Sjoerg   LibraryPaths.emplace_back(DefaultLibPath.c_str());
1698*e038c9c4Sjoerg 
1699*e038c9c4Sjoerg   OptSpecifier LibomptargetBCPathOpt =
1700*e038c9c4Sjoerg       Triple.isAMDGCN() ? options::OPT_libomptarget_amdgcn_bc_path_EQ
1701*e038c9c4Sjoerg                         : options::OPT_libomptarget_nvptx_bc_path_EQ;
1702*e038c9c4Sjoerg 
1703*e038c9c4Sjoerg   StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgcn" : "nvptx";
1704*e038c9c4Sjoerg   // First check whether user specifies bc library
1705*e038c9c4Sjoerg   if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) {
1706*e038c9c4Sjoerg     std::string LibOmpTargetName(A->getValue());
1707*e038c9c4Sjoerg     if (llvm::sys::fs::exists(LibOmpTargetName)) {
1708*e038c9c4Sjoerg       CC1Args.push_back("-mlink-builtin-bitcode");
1709*e038c9c4Sjoerg       CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetName));
1710*e038c9c4Sjoerg     } else {
1711*e038c9c4Sjoerg       D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
1712*e038c9c4Sjoerg           << LibOmpTargetName;
1713*e038c9c4Sjoerg     }
1714*e038c9c4Sjoerg   } else {
1715*e038c9c4Sjoerg     bool FoundBCLibrary = false;
1716*e038c9c4Sjoerg 
1717*e038c9c4Sjoerg     std::string LibOmpTargetName =
1718*e038c9c4Sjoerg         "libomptarget-" + BitcodeSuffix.str() + ".bc";
1719*e038c9c4Sjoerg 
1720*e038c9c4Sjoerg     for (StringRef LibraryPath : LibraryPaths) {
1721*e038c9c4Sjoerg       SmallString<128> LibOmpTargetFile(LibraryPath);
1722*e038c9c4Sjoerg       llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
1723*e038c9c4Sjoerg       if (llvm::sys::fs::exists(LibOmpTargetFile)) {
1724*e038c9c4Sjoerg         CC1Args.push_back("-mlink-builtin-bitcode");
1725*e038c9c4Sjoerg         CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
1726*e038c9c4Sjoerg         FoundBCLibrary = true;
17277330f729Sjoerg         break;
17287330f729Sjoerg       }
1729*e038c9c4Sjoerg     }
1730*e038c9c4Sjoerg 
1731*e038c9c4Sjoerg     if (!FoundBCLibrary)
1732*e038c9c4Sjoerg       D.Diag(diag::err_drv_omp_offload_target_missingbcruntime)
1733*e038c9c4Sjoerg           << LibOmpTargetName << ArchPrefix;
1734*e038c9c4Sjoerg   }
17357330f729Sjoerg }
1736