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