• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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::ppc64:
393   case llvm::Triple::ppc64le: {
394     std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
395     // LLVM may default to generating code for the native CPU,
396     // but, like gcc, we default to a more generic option for
397     // each architecture. (except on AIX)
398     if (!TargetCPUName.empty())
399       return TargetCPUName;
400 
401     if (T.isOSAIX())
402       TargetCPUName = "pwr4";
403     else if (T.getArch() == llvm::Triple::ppc64le)
404       TargetCPUName = "ppc64le";
405     else if (T.getArch() == llvm::Triple::ppc64)
406       TargetCPUName = "ppc64";
407     else
408       TargetCPUName = "ppc";
409 
410     return TargetCPUName;
411   }
412   case llvm::Triple::riscv32:
413   case llvm::Triple::riscv64:
414     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
415       return A->getValue();
416     return "";
417 
418   case llvm::Triple::bpfel:
419   case llvm::Triple::bpfeb:
420   case llvm::Triple::sparc:
421   case llvm::Triple::sparcel:
422   case llvm::Triple::sparcv9:
423     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
424       return A->getValue();
425     if (T.getArch() == llvm::Triple::sparc && T.isOSSolaris())
426       return "v9";
427     return "";
428 
429   case llvm::Triple::x86:
430   case llvm::Triple::x86_64:
431     return x86::getX86TargetCPU(Args, T);
432 
433   case llvm::Triple::hexagon:
434     return "hexagon" +
435            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
436 
437   case llvm::Triple::lanai:
438     return getLanaiTargetCPU(Args);
439 
440   case llvm::Triple::systemz:
441     return systemz::getSystemZTargetCPU(Args);
442 
443   case llvm::Triple::r600:
444   case llvm::Triple::amdgcn:
445     return getAMDGPUTargetGPU(T, Args);
446 
447   case llvm::Triple::wasm32:
448   case llvm::Triple::wasm64:
449     return std::string(getWebAssemblyTargetCPU(Args));
450   }
451 }
452 
getLTOParallelism(const ArgList & Args,const Driver & D)453 llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
454   Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
455   if (!LtoJobsArg)
456     return {};
457   if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue()))
458     D.Diag(diag::err_drv_invalid_int_value)
459         << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
460   return LtoJobsArg->getValue();
461 }
462 
463 // CloudABI uses -ffunction-sections and -fdata-sections by default.
isUseSeparateSections(const llvm::Triple & Triple)464 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
465   return Triple.getOS() == llvm::Triple::CloudABI;
466 }
467 
addLTOOptions(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfo & Input,bool IsThinLTO)468 void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
469                           ArgStringList &CmdArgs, const InputInfo &Output,
470                           const InputInfo &Input, bool IsThinLTO) {
471   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
472   const Driver &D = ToolChain.getDriver();
473   if (llvm::sys::path::filename(Linker) != "ld.lld" &&
474       llvm::sys::path::stem(Linker) != "ld.lld") {
475     // Tell the linker to load the plugin. This has to come before
476     // AddLinkerInputs as gold requires -plugin to come before any -plugin-opt
477     // that -Wl might forward.
478     CmdArgs.push_back("-plugin");
479 
480 #if defined(_WIN32)
481     const char *Suffix = ".dll";
482 #elif defined(__APPLE__)
483     const char *Suffix = ".dylib";
484 #else
485     const char *Suffix = ".so";
486 #endif
487 
488     SmallString<1024> Plugin;
489     llvm::sys::path::native(
490         Twine(D.Dir) + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" + Suffix,
491         Plugin);
492     CmdArgs.push_back(Args.MakeArgString(Plugin));
493   }
494 
495   // Try to pass driver level flags relevant to LTO code generation down to
496   // the plugin.
497 
498   // Handle flags for selecting CPU variants.
499   std::string CPU = getCPUName(Args, ToolChain.getTriple());
500   if (!CPU.empty())
501     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
502 
503   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
504     // The optimization level matches
505     // CompilerInvocation.cpp:getOptimizationLevel().
506     StringRef OOpt;
507     if (A->getOption().matches(options::OPT_O4) ||
508         A->getOption().matches(options::OPT_Ofast))
509       OOpt = "3";
510     else if (A->getOption().matches(options::OPT_O)) {
511       OOpt = A->getValue();
512       if (OOpt == "g")
513         OOpt = "1";
514       else if (OOpt == "s" || OOpt == "z")
515         OOpt = "2";
516     } else if (A->getOption().matches(options::OPT_O0))
517       OOpt = "0";
518     if (!OOpt.empty())
519       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
520   }
521 
522   if (Args.hasArg(options::OPT_gsplit_dwarf)) {
523     CmdArgs.push_back(
524         Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
525             Output.getFilename() + "_dwo"));
526   }
527 
528   if (IsThinLTO)
529     CmdArgs.push_back("-plugin-opt=thinlto");
530 
531   StringRef Parallelism = getLTOParallelism(Args, D);
532   if (!Parallelism.empty())
533     CmdArgs.push_back(
534         Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
535 
536   // If an explicit debugger tuning argument appeared, pass it along.
537   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
538                                options::OPT_ggdbN_Group)) {
539     if (A->getOption().matches(options::OPT_glldb))
540       CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
541     else if (A->getOption().matches(options::OPT_gsce))
542       CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
543     else
544       CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
545   }
546 
547   bool UseSeparateSections =
548       isUseSeparateSections(ToolChain.getEffectiveTriple());
549 
550   if (Args.hasFlag(options::OPT_ffunction_sections,
551                    options::OPT_fno_function_sections, UseSeparateSections)) {
552     CmdArgs.push_back("-plugin-opt=-function-sections");
553   }
554 
555   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
556                    UseSeparateSections)) {
557     CmdArgs.push_back("-plugin-opt=-data-sections");
558   }
559 
560   if (Arg *A = getLastProfileSampleUseArg(Args)) {
561     StringRef FName = A->getValue();
562     if (!llvm::sys::fs::exists(FName))
563       D.Diag(diag::err_drv_no_such_file) << FName;
564     else
565       CmdArgs.push_back(
566           Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
567   }
568 
569   auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
570                                            options::OPT_fcs_profile_generate_EQ,
571                                            options::OPT_fno_profile_generate);
572   if (CSPGOGenerateArg &&
573       CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
574     CSPGOGenerateArg = nullptr;
575 
576   auto *ProfileUseArg = getLastProfileUseArg(Args);
577 
578   if (CSPGOGenerateArg) {
579     CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate"));
580     if (CSPGOGenerateArg->getOption().matches(
581             options::OPT_fcs_profile_generate_EQ)) {
582       SmallString<128> Path(CSPGOGenerateArg->getValue());
583       llvm::sys::path::append(Path, "default_%m.profraw");
584       CmdArgs.push_back(
585           Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path));
586     } else
587       CmdArgs.push_back(
588           Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw"));
589   } else if (ProfileUseArg) {
590     SmallString<128> Path(
591         ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
592     if (Path.empty() || llvm::sys::fs::is_directory(Path))
593       llvm::sys::path::append(Path, "default.profdata");
594     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") +
595                                          Path));
596   }
597 
598   // Need this flag to turn on new pass manager via Gold plugin.
599   if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager,
600                    options::OPT_fno_experimental_new_pass_manager,
601                    /* Default */ LLVM_ENABLE_NEW_PASS_MANAGER)) {
602     CmdArgs.push_back("-plugin-opt=new-pass-manager");
603   }
604 
605   // Setup statistics file output.
606   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
607   if (!StatsFile.empty())
608     CmdArgs.push_back(
609         Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
610 
611   addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true);
612 
613   // Handle remark diagnostics on screen options: '-Rpass-*'.
614   renderRpassOptions(Args, CmdArgs);
615 
616   // Handle serialized remarks options: '-fsave-optimization-record'
617   // and '-foptimization-record-*'.
618   if (willEmitRemarks(Args))
619     renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input,
620                          Output);
621 
622   // Handle remarks hotness/threshold related options.
623   renderRemarksHotnessOptions(Args, CmdArgs);
624 }
625 
addArchSpecificRPath(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)626 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
627                                  ArgStringList &CmdArgs) {
628   // Enable -frtlib-add-rpath by default for the case of VE.
629   const bool IsVE = TC.getTriple().isVE();
630   bool DefaultValue = IsVE;
631   if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
632                     options::OPT_fno_rtlib_add_rpath, DefaultValue))
633     return;
634 
635   std::string CandidateRPath = TC.getArchSpecificLibPath();
636   if (TC.getVFS().exists(CandidateRPath)) {
637     CmdArgs.push_back("-rpath");
638     CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
639   }
640 }
641 
addOpenMPRuntime(ArgStringList & CmdArgs,const ToolChain & TC,const ArgList & Args,bool ForceStaticHostRuntime,bool IsOffloadingHost,bool GompNeedsRT)642 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
643                              const ArgList &Args, bool ForceStaticHostRuntime,
644                              bool IsOffloadingHost, bool GompNeedsRT) {
645   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
646                     options::OPT_fno_openmp, false))
647     return false;
648 
649   Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
650 
651   if (RTKind == Driver::OMPRT_Unknown)
652     // Already diagnosed.
653     return false;
654 
655   if (ForceStaticHostRuntime)
656     CmdArgs.push_back("-Bstatic");
657 
658   switch (RTKind) {
659   case Driver::OMPRT_OMP:
660     CmdArgs.push_back("-lomp");
661     break;
662   case Driver::OMPRT_GOMP:
663     CmdArgs.push_back("-lgomp");
664     break;
665   case Driver::OMPRT_IOMP5:
666     CmdArgs.push_back("-liomp5");
667     break;
668   case Driver::OMPRT_Unknown:
669     break;
670   }
671 
672   if (ForceStaticHostRuntime)
673     CmdArgs.push_back("-Bdynamic");
674 
675   if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
676       CmdArgs.push_back("-lrt");
677 
678   if (IsOffloadingHost)
679     CmdArgs.push_back("-lomptarget");
680 
681   addArchSpecificRPath(TC, Args, CmdArgs);
682 
683   return true;
684 }
685 
addSanitizerRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer,bool IsShared,bool IsWhole)686 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
687                                 ArgStringList &CmdArgs, StringRef Sanitizer,
688                                 bool IsShared, bool IsWhole) {
689   // Wrap any static runtimes that must be forced into executable in
690   // whole-archive.
691   if (IsWhole) CmdArgs.push_back("--whole-archive");
692   CmdArgs.push_back(TC.getCompilerRTArgString(
693       Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
694   if (IsWhole) CmdArgs.push_back("--no-whole-archive");
695 
696   if (IsShared) {
697     addArchSpecificRPath(TC, Args, CmdArgs);
698   }
699 }
700 
701 // Tries to use a file with the list of dynamic symbols that need to be exported
702 // from the runtime library. Returns true if the file was found.
addSanitizerDynamicList(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer)703 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
704                                     ArgStringList &CmdArgs,
705                                     StringRef Sanitizer) {
706   // Solaris ld defaults to --export-dynamic behaviour but doesn't support
707   // the option, so don't try to pass it.
708   if (TC.getTriple().getOS() == llvm::Triple::Solaris)
709     return true;
710   // Myriad is static linking only.  Furthermore, some versions of its
711   // linker have the bug where --export-dynamic overrides -static, so
712   // don't use --export-dynamic on that platform.
713   if (TC.getTriple().getVendor() == llvm::Triple::Myriad)
714     return true;
715   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
716   if (llvm::sys::fs::exists(SanRT + ".syms")) {
717     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
718     return true;
719   }
720   return false;
721 }
722 
getAsNeededOption(const ToolChain & TC,bool as_needed)723 static const char *getAsNeededOption(const ToolChain &TC, bool as_needed) {
724   // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
725   // for the native forms -z ignore/-z record, they are missing in Illumos,
726   // so always use the native form.
727   if (TC.getTriple().isOSSolaris())
728     return as_needed ? "-zignore" : "-zrecord";
729   else
730     return as_needed ? "--as-needed" : "--no-as-needed";
731 }
732 
linkSanitizerRuntimeDeps(const ToolChain & TC,ArgStringList & CmdArgs)733 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
734                                      ArgStringList &CmdArgs) {
735   // Fuchsia never needs these.  Any sanitizer runtimes with system
736   // dependencies use the `.deplibs` feature instead.
737   if (TC.getTriple().isOSFuchsia())
738     return;
739 
740   // Force linking against the system libraries sanitizers depends on
741   // (see PR15823 why this is necessary).
742   CmdArgs.push_back(getAsNeededOption(TC, false));
743   // There's no libpthread or librt on RTEMS & Android.
744   if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
745       !TC.getTriple().isAndroid()) {
746     CmdArgs.push_back("-lpthread");
747     if (!TC.getTriple().isOSOpenBSD())
748       CmdArgs.push_back("-lrt");
749   }
750   CmdArgs.push_back("-lm");
751   // There's no libdl on all OSes.
752   if (!TC.getTriple().isOSFreeBSD() &&
753       !TC.getTriple().isOSNetBSD() &&
754       !TC.getTriple().isOSOpenBSD() &&
755        TC.getTriple().getOS() != llvm::Triple::RTEMS)
756     CmdArgs.push_back("-ldl");
757   // Required for backtrace on some OSes
758   if (TC.getTriple().isOSFreeBSD() ||
759       TC.getTriple().isOSNetBSD())
760     CmdArgs.push_back("-lexecinfo");
761 }
762 
763 static void
collectSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,SmallVectorImpl<StringRef> & SharedRuntimes,SmallVectorImpl<StringRef> & StaticRuntimes,SmallVectorImpl<StringRef> & NonWholeStaticRuntimes,SmallVectorImpl<StringRef> & HelperStaticRuntimes,SmallVectorImpl<StringRef> & RequiredSymbols)764 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
765                          SmallVectorImpl<StringRef> &SharedRuntimes,
766                          SmallVectorImpl<StringRef> &StaticRuntimes,
767                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
768                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
769                          SmallVectorImpl<StringRef> &RequiredSymbols) {
770   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
771   // Collect shared runtimes.
772   if (SanArgs.needsSharedRt()) {
773     if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
774       SharedRuntimes.push_back("asan");
775       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
776         HelperStaticRuntimes.push_back("asan-preinit");
777     }
778     if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) {
779       SharedRuntimes.push_back("memprof");
780       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
781         HelperStaticRuntimes.push_back("memprof-preinit");
782     }
783     if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
784       if (SanArgs.requiresMinimalRuntime())
785         SharedRuntimes.push_back("ubsan_minimal");
786       else
787         SharedRuntimes.push_back("ubsan_standalone");
788     }
789     if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
790       if (SanArgs.requiresMinimalRuntime())
791         SharedRuntimes.push_back("scudo_minimal");
792       else
793         SharedRuntimes.push_back("scudo");
794     }
795     if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes())
796       SharedRuntimes.push_back("tsan");
797     if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes())
798       SharedRuntimes.push_back("hwasan");
799   }
800 
801   // The stats_client library is also statically linked into DSOs.
802   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
803     StaticRuntimes.push_back("stats_client");
804 
805   // Collect static runtimes.
806   if (Args.hasArg(options::OPT_shared)) {
807     // Don't link static runtimes into DSOs.
808     return;
809   }
810 
811   // Each static runtime that has a DSO counterpart above is excluded below,
812   // but runtimes that exist only as static are not affected by needsSharedRt.
813 
814   if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
815     StaticRuntimes.push_back("asan");
816     if (SanArgs.linkCXXRuntimes())
817       StaticRuntimes.push_back("asan_cxx");
818   }
819 
820   if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt() &&
821       SanArgs.linkRuntimes()) {
822     StaticRuntimes.push_back("memprof");
823     if (SanArgs.linkCXXRuntimes())
824       StaticRuntimes.push_back("memprof_cxx");
825   }
826 
827   if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
828     StaticRuntimes.push_back("hwasan");
829     if (SanArgs.linkCXXRuntimes())
830       StaticRuntimes.push_back("hwasan_cxx");
831   }
832   if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes())
833     StaticRuntimes.push_back("dfsan");
834   if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes())
835     StaticRuntimes.push_back("lsan");
836   if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) {
837     StaticRuntimes.push_back("msan");
838     if (SanArgs.linkCXXRuntimes())
839       StaticRuntimes.push_back("msan_cxx");
840   }
841   if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt() &&
842       SanArgs.linkRuntimes()) {
843     StaticRuntimes.push_back("tsan");
844     if (SanArgs.linkCXXRuntimes())
845       StaticRuntimes.push_back("tsan_cxx");
846   }
847   if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
848     if (SanArgs.requiresMinimalRuntime()) {
849       StaticRuntimes.push_back("ubsan_minimal");
850     } else {
851       StaticRuntimes.push_back("ubsan_standalone");
852       if (SanArgs.linkCXXRuntimes())
853         StaticRuntimes.push_back("ubsan_standalone_cxx");
854     }
855   }
856   if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) {
857     NonWholeStaticRuntimes.push_back("safestack");
858     RequiredSymbols.push_back("__safestack_init");
859   }
860   if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) {
861     if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
862       StaticRuntimes.push_back("cfi");
863     if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) {
864       StaticRuntimes.push_back("cfi_diag");
865       if (SanArgs.linkCXXRuntimes())
866         StaticRuntimes.push_back("ubsan_standalone_cxx");
867     }
868   }
869   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) {
870     NonWholeStaticRuntimes.push_back("stats");
871     RequiredSymbols.push_back("__sanitizer_stats_register");
872   }
873   if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
874     if (SanArgs.requiresMinimalRuntime()) {
875       StaticRuntimes.push_back("scudo_minimal");
876       if (SanArgs.linkCXXRuntimes())
877         StaticRuntimes.push_back("scudo_cxx_minimal");
878     } else {
879       StaticRuntimes.push_back("scudo");
880       if (SanArgs.linkCXXRuntimes())
881         StaticRuntimes.push_back("scudo_cxx");
882     }
883   }
884 }
885 
886 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
887 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
addSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)888 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
889                                  ArgStringList &CmdArgs) {
890   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
891       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
892   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
893                            NonWholeStaticRuntimes, HelperStaticRuntimes,
894                            RequiredSymbols);
895 
896   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
897   // Inject libfuzzer dependencies.
898   if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
899       !Args.hasArg(options::OPT_shared)) {
900 
901     addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
902     if (SanArgs.needsFuzzerInterceptors())
903       addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
904                           true);
905     if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
906       bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
907                                  !Args.hasArg(options::OPT_static);
908       if (OnlyLibstdcxxStatic)
909         CmdArgs.push_back("-Bstatic");
910       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
911       if (OnlyLibstdcxxStatic)
912         CmdArgs.push_back("-Bdynamic");
913     }
914   }
915 
916   for (auto RT : SharedRuntimes)
917     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
918   for (auto RT : HelperStaticRuntimes)
919     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
920   bool AddExportDynamic = false;
921   for (auto RT : StaticRuntimes) {
922     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
923     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
924   }
925   for (auto RT : NonWholeStaticRuntimes) {
926     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
927     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
928   }
929   for (auto S : RequiredSymbols) {
930     CmdArgs.push_back("-u");
931     CmdArgs.push_back(Args.MakeArgString(S));
932   }
933   // If there is a static runtime with no dynamic list, force all the symbols
934   // to be dynamic to be sure we export sanitizer interface functions.
935   if (AddExportDynamic)
936     CmdArgs.push_back("--export-dynamic");
937 
938   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
939     CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
940 
941   return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
942 }
943 
addXRayRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)944 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
945   if (Args.hasArg(options::OPT_shared))
946     return false;
947 
948   if (TC.getXRayArgs().needsXRayRt()) {
949     CmdArgs.push_back("-whole-archive");
950     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
951     for (const auto &Mode : TC.getXRayArgs().modeList())
952       CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
953     CmdArgs.push_back("-no-whole-archive");
954     return true;
955   }
956 
957   return false;
958 }
959 
linkXRayRuntimeDeps(const ToolChain & TC,ArgStringList & CmdArgs)960 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
961   CmdArgs.push_back(getAsNeededOption(TC, false));
962   CmdArgs.push_back("-lpthread");
963   if (!TC.getTriple().isOSOpenBSD())
964     CmdArgs.push_back("-lrt");
965   CmdArgs.push_back("-lm");
966 
967   if (!TC.getTriple().isOSFreeBSD() &&
968       !TC.getTriple().isOSNetBSD() &&
969       !TC.getTriple().isOSOpenBSD())
970     CmdArgs.push_back("-ldl");
971 }
972 
areOptimizationsEnabled(const ArgList & Args)973 bool tools::areOptimizationsEnabled(const ArgList &Args) {
974   // Find the last -O arg and see if it is non-zero.
975   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
976     return !A->getOption().matches(options::OPT_O0);
977   // Defaults to -O0.
978   return false;
979 }
980 
SplitDebugName(const JobAction & JA,const ArgList & Args,const InputInfo & Input,const InputInfo & Output)981 const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
982                                   const InputInfo &Input,
983                                   const InputInfo &Output) {
984   auto AddPostfix = [JA](auto &F) {
985     if (JA.getOffloadingDeviceKind() == Action::OFK_HIP)
986       F += (Twine("_") + JA.getOffloadingArch()).str();
987     F += ".dwo";
988   };
989   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
990     if (StringRef(A->getValue()) == "single")
991       return Args.MakeArgString(Output.getFilename());
992 
993   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
994   if (FinalOutput && Args.hasArg(options::OPT_c)) {
995     SmallString<128> T(FinalOutput->getValue());
996     llvm::sys::path::remove_filename(T);
997     llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue()));
998     AddPostfix(T);
999     return Args.MakeArgString(T);
1000   } else {
1001     // Use the compilation dir.
1002     SmallString<128> T(
1003         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
1004     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
1005     AddPostfix(F);
1006     T += F;
1007     return Args.MakeArgString(F);
1008   }
1009 }
1010 
SplitDebugInfo(const ToolChain & TC,Compilation & C,const Tool & T,const JobAction & JA,const ArgList & Args,const InputInfo & Output,const char * OutFile)1011 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
1012                            const JobAction &JA, const ArgList &Args,
1013                            const InputInfo &Output, const char *OutFile) {
1014   ArgStringList ExtractArgs;
1015   ExtractArgs.push_back("--extract-dwo");
1016 
1017   ArgStringList StripArgs;
1018   StripArgs.push_back("--strip-dwo");
1019 
1020   // Grabbing the output of the earlier compile step.
1021   StripArgs.push_back(Output.getFilename());
1022   ExtractArgs.push_back(Output.getFilename());
1023   ExtractArgs.push_back(OutFile);
1024 
1025   const char *Exec =
1026       Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
1027   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1028 
1029   // First extract the dwo sections.
1030   C.addCommand(std::make_unique<Command>(JA, T,
1031                                          ResponseFileSupport::AtFileCurCP(),
1032                                          Exec, ExtractArgs, II, Output));
1033 
1034   // Then remove them from the original .o file.
1035   C.addCommand(std::make_unique<Command>(
1036       JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
1037 }
1038 
1039 // Claim options we don't want to warn if they are unused. We do this for
1040 // options that build systems might add but are unused when assembling or only
1041 // running the preprocessor for example.
claimNoWarnArgs(const ArgList & Args)1042 void tools::claimNoWarnArgs(const ArgList &Args) {
1043   // Don't warn about unused -f(no-)?lto.  This can happen when we're
1044   // preprocessing, precompiling or assembling.
1045   Args.ClaimAllArgs(options::OPT_flto_EQ);
1046   Args.ClaimAllArgs(options::OPT_flto);
1047   Args.ClaimAllArgs(options::OPT_fno_lto);
1048 }
1049 
getLastProfileUseArg(const ArgList & Args)1050 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
1051   auto *ProfileUseArg = Args.getLastArg(
1052       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
1053       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
1054       options::OPT_fno_profile_instr_use);
1055 
1056   if (ProfileUseArg &&
1057       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
1058     ProfileUseArg = nullptr;
1059 
1060   return ProfileUseArg;
1061 }
1062 
getLastProfileSampleUseArg(const ArgList & Args)1063 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
1064   auto *ProfileSampleUseArg = Args.getLastArg(
1065       options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
1066       options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
1067       options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
1068 
1069   if (ProfileSampleUseArg &&
1070       (ProfileSampleUseArg->getOption().matches(
1071            options::OPT_fno_profile_sample_use) ||
1072        ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
1073     return nullptr;
1074 
1075   return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
1076                          options::OPT_fauto_profile_EQ);
1077 }
1078 
1079 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
1080 /// smooshes them together with platform defaults, to decide whether
1081 /// this compile should be using PIC mode or not. Returns a tuple of
1082 /// (RelocationModel, PICLevel, IsPIE).
1083 std::tuple<llvm::Reloc::Model, unsigned, bool>
ParsePICArgs(const ToolChain & ToolChain,const ArgList & Args)1084 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
1085   const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
1086   const llvm::Triple &Triple = ToolChain.getTriple();
1087 
1088   bool PIE = ToolChain.isPIEDefault();
1089   bool PIC = PIE || ToolChain.isPICDefault();
1090   // The Darwin/MachO default to use PIC does not apply when using -static.
1091   if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
1092     PIE = PIC = false;
1093   bool IsPICLevelTwo = PIC;
1094 
1095   bool KernelOrKext =
1096       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1097 
1098   // Android-specific defaults for PIC/PIE
1099   if (Triple.isAndroid()) {
1100     switch (Triple.getArch()) {
1101     case llvm::Triple::arm:
1102     case llvm::Triple::armeb:
1103     case llvm::Triple::thumb:
1104     case llvm::Triple::thumbeb:
1105     case llvm::Triple::aarch64:
1106     case llvm::Triple::mips:
1107     case llvm::Triple::mipsel:
1108     case llvm::Triple::mips64:
1109     case llvm::Triple::mips64el:
1110       PIC = true; // "-fpic"
1111       break;
1112 
1113     case llvm::Triple::x86:
1114     case llvm::Triple::x86_64:
1115       PIC = true; // "-fPIC"
1116       IsPICLevelTwo = true;
1117       break;
1118 
1119     default:
1120       break;
1121     }
1122   }
1123 
1124   // OpenBSD-specific defaults for PIE
1125   if (Triple.isOSOpenBSD()) {
1126     switch (ToolChain.getArch()) {
1127     case llvm::Triple::arm:
1128     case llvm::Triple::aarch64:
1129     case llvm::Triple::mips64:
1130     case llvm::Triple::mips64el:
1131     case llvm::Triple::x86:
1132     case llvm::Triple::x86_64:
1133       IsPICLevelTwo = false; // "-fpie"
1134       break;
1135 
1136     case llvm::Triple::ppc:
1137     case llvm::Triple::sparcv9:
1138       IsPICLevelTwo = true; // "-fPIE"
1139       break;
1140 
1141     default:
1142       break;
1143     }
1144   }
1145 
1146   // AMDGPU-specific defaults for PIC.
1147   if (Triple.getArch() == llvm::Triple::amdgcn)
1148     PIC = true;
1149 
1150   // The last argument relating to either PIC or PIE wins, and no
1151   // other argument is used. If the last argument is any flavor of the
1152   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1153   // option implicitly enables PIC at the same level.
1154   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1155                                     options::OPT_fpic, options::OPT_fno_pic,
1156                                     options::OPT_fPIE, options::OPT_fno_PIE,
1157                                     options::OPT_fpie, options::OPT_fno_pie);
1158   if (Triple.isOSWindows() && LastPICArg &&
1159       LastPICArg ==
1160           Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1161                           options::OPT_fPIE, options::OPT_fpie)) {
1162     ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1163         << LastPICArg->getSpelling() << Triple.str();
1164     if (Triple.getArch() == llvm::Triple::x86_64)
1165       return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1166     return std::make_tuple(llvm::Reloc::Static, 0U, false);
1167   }
1168 
1169   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1170   // is forced, then neither PIC nor PIE flags will have no effect.
1171   if (!ToolChain.isPICDefaultForced()) {
1172     if (LastPICArg) {
1173       Option O = LastPICArg->getOption();
1174       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1175           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1176         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1177         PIC =
1178             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1179         IsPICLevelTwo =
1180             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1181       } else {
1182         PIE = PIC = false;
1183         if (EffectiveTriple.isPS4CPU()) {
1184           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1185           StringRef Model = ModelArg ? ModelArg->getValue() : "";
1186           if (Model != "kernel") {
1187             PIC = true;
1188             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
1189                 << LastPICArg->getSpelling();
1190           }
1191         }
1192       }
1193     }
1194   }
1195 
1196   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
1197   // PIC level would've been set to level 1, force it back to level 2 PIC
1198   // instead.
1199   if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
1200     IsPICLevelTwo |= ToolChain.isPICDefault();
1201 
1202   // This kernel flags are a trump-card: they will disable PIC/PIE
1203   // generation, independent of the argument order.
1204   if (KernelOrKext &&
1205       ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1206        !EffectiveTriple.isWatchOS()))
1207     PIC = PIE = false;
1208 
1209   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1210     // This is a very special mode. It trumps the other modes, almost no one
1211     // uses it, and it isn't even valid on any OS but Darwin.
1212     if (!Triple.isOSDarwin())
1213       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1214           << A->getSpelling() << Triple.str();
1215 
1216     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1217 
1218     // Only a forced PIC mode can cause the actual compile to have PIC defines
1219     // etc., no flags are sufficient. This behavior was selected to closely
1220     // match that of llvm-gcc and Apple GCC before that.
1221     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1222 
1223     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1224   }
1225 
1226   bool EmbeddedPISupported;
1227   switch (Triple.getArch()) {
1228     case llvm::Triple::arm:
1229     case llvm::Triple::armeb:
1230     case llvm::Triple::thumb:
1231     case llvm::Triple::thumbeb:
1232       EmbeddedPISupported = true;
1233       break;
1234     default:
1235       EmbeddedPISupported = false;
1236       break;
1237   }
1238 
1239   bool ROPI = false, RWPI = false;
1240   Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1241   if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1242     if (!EmbeddedPISupported)
1243       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1244           << LastROPIArg->getSpelling() << Triple.str();
1245     ROPI = true;
1246   }
1247   Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1248   if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1249     if (!EmbeddedPISupported)
1250       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1251           << LastRWPIArg->getSpelling() << Triple.str();
1252     RWPI = true;
1253   }
1254 
1255   // ROPI and RWPI are not compatible with PIC or PIE.
1256   if ((ROPI || RWPI) && (PIC || PIE))
1257     ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1258 
1259   if (Triple.isMIPS()) {
1260     StringRef CPUName;
1261     StringRef ABIName;
1262     mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1263     // When targeting the N64 ABI, PIC is the default, except in the case
1264     // when the -mno-abicalls option is used. In that case we exit
1265     // at next check regardless of PIC being set below.
1266     if (ABIName == "n64")
1267       PIC = true;
1268     // When targettng MIPS with -mno-abicalls, it's always static.
1269     if(Args.hasArg(options::OPT_mno_abicalls))
1270       return std::make_tuple(llvm::Reloc::Static, 0U, false);
1271     // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1272     // does not use PIC level 2 for historical reasons.
1273     IsPICLevelTwo = false;
1274   }
1275 
1276   if (PIC)
1277     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1278 
1279   llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1280   if (ROPI && RWPI)
1281     RelocM = llvm::Reloc::ROPI_RWPI;
1282   else if (ROPI)
1283     RelocM = llvm::Reloc::ROPI;
1284   else if (RWPI)
1285     RelocM = llvm::Reloc::RWPI;
1286 
1287   return std::make_tuple(RelocM, 0U, false);
1288 }
1289 
1290 // `-falign-functions` indicates that the functions should be aligned to a
1291 // 16-byte boundary.
1292 //
1293 // `-falign-functions=1` is the same as `-fno-align-functions`.
1294 //
1295 // The scalar `n` in `-falign-functions=n` must be an integral value between
1296 // [0, 65536].  If the value is not a power-of-two, it will be rounded up to
1297 // the nearest power-of-two.
1298 //
1299 // If we return `0`, the frontend will default to the backend's preferred
1300 // alignment.
1301 //
1302 // NOTE: icc only allows values between [0, 4096].  icc uses `-falign-functions`
1303 // to mean `-falign-functions=16`.  GCC defaults to the backend's preferred
1304 // alignment.  For unaligned functions, we default to the backend's preferred
1305 // alignment.
ParseFunctionAlignment(const ToolChain & TC,const ArgList & Args)1306 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1307                                        const ArgList &Args) {
1308   const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1309                                  options::OPT_falign_functions_EQ,
1310                                  options::OPT_fno_align_functions);
1311   if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1312     return 0;
1313 
1314   if (A->getOption().matches(options::OPT_falign_functions))
1315     return 0;
1316 
1317   unsigned Value = 0;
1318   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1319     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1320         << A->getAsString(Args) << A->getValue();
1321   return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1322 }
1323 
ParseDebugDefaultVersion(const ToolChain & TC,const ArgList & Args)1324 unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC,
1325                                          const ArgList &Args) {
1326   const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
1327 
1328   if (!A)
1329     return 0;
1330 
1331   unsigned Value = 0;
1332   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
1333       Value < 2)
1334     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1335         << A->getAsString(Args) << A->getValue();
1336   return Value;
1337 }
1338 
AddAssemblerKPIC(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs)1339 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1340                              ArgStringList &CmdArgs) {
1341   llvm::Reloc::Model RelocationModel;
1342   unsigned PICLevel;
1343   bool IsPIE;
1344   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1345 
1346   if (RelocationModel != llvm::Reloc::Static)
1347     CmdArgs.push_back("-KPIC");
1348 }
1349 
1350 /// Determine whether Objective-C automated reference counting is
1351 /// enabled.
isObjCAutoRefCount(const ArgList & Args)1352 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1353   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1354 }
1355 
1356 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
1357 
getLibGccType(const Driver & D,const ArgList & Args)1358 static LibGccType getLibGccType(const Driver &D, const ArgList &Args) {
1359   if (Args.hasArg(options::OPT_static_libgcc) ||
1360       Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie))
1361     return LibGccType::StaticLibGcc;
1362   if (Args.hasArg(options::OPT_shared_libgcc) || D.CCCIsCXX())
1363     return LibGccType::SharedLibGcc;
1364   return LibGccType::UnspecifiedLibGcc;
1365 }
1366 
1367 // Gcc adds libgcc arguments in various ways:
1368 //
1369 // gcc <none>:     -lgcc --as-needed -lgcc_s --no-as-needed
1370 // g++ <none>:                       -lgcc_s               -lgcc
1371 // gcc shared:                       -lgcc_s               -lgcc
1372 // g++ shared:                       -lgcc_s               -lgcc
1373 // gcc static:     -lgcc             -lgcc_eh
1374 // g++ static:     -lgcc             -lgcc_eh
1375 // gcc static-pie: -lgcc             -lgcc_eh
1376 // g++ static-pie: -lgcc             -lgcc_eh
1377 //
1378 // Also, certain targets need additional adjustments.
1379 
AddUnwindLibrary(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)1380 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
1381                              ArgStringList &CmdArgs, const ArgList &Args) {
1382   ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
1383   // Targets that don't use unwind libraries.
1384   if (TC.getTriple().isAndroid() || TC.getTriple().isOSIAMCU() ||
1385       TC.getTriple().isOSBinFormatWasm() ||
1386       UNW == ToolChain::UNW_None)
1387     return;
1388 
1389   LibGccType LGT = getLibGccType(D, Args);
1390   bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
1391                   !TC.getTriple().isAndroid() && !TC.getTriple().isOSCygMing();
1392   if (AsNeeded)
1393     CmdArgs.push_back(getAsNeededOption(TC, true));
1394 
1395   switch (UNW) {
1396   case ToolChain::UNW_None:
1397     return;
1398   case ToolChain::UNW_Libgcc: {
1399     if (LGT == LibGccType::StaticLibGcc)
1400       CmdArgs.push_back("-lgcc_eh");
1401     else
1402       CmdArgs.push_back("-lgcc_s");
1403     break;
1404   }
1405   case ToolChain::UNW_CompilerRT:
1406     if (LGT == LibGccType::StaticLibGcc)
1407       CmdArgs.push_back("-l:libunwind.a");
1408     else if (TC.getTriple().isOSCygMing()) {
1409       if (LGT == LibGccType::SharedLibGcc)
1410         CmdArgs.push_back("-l:libunwind.dll.a");
1411       else
1412         // Let the linker choose between libunwind.dll.a and libunwind.a
1413         // depending on what's available, and depending on the -static flag
1414         CmdArgs.push_back("-lunwind");
1415     } else
1416       CmdArgs.push_back("-l:libunwind.so");
1417     break;
1418   }
1419 
1420   if (AsNeeded)
1421     CmdArgs.push_back(getAsNeededOption(TC, false));
1422 }
1423 
AddLibgcc(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)1424 static void AddLibgcc(const ToolChain &TC, const Driver &D,
1425                       ArgStringList &CmdArgs, const ArgList &Args) {
1426   LibGccType LGT = getLibGccType(D, Args);
1427   if (LGT != LibGccType::SharedLibGcc)
1428     CmdArgs.push_back("-lgcc");
1429   AddUnwindLibrary(TC, D, CmdArgs, Args);
1430   if (LGT == LibGccType::SharedLibGcc)
1431     CmdArgs.push_back("-lgcc");
1432 
1433   // According to Android ABI, we have to link with libdl if we are
1434   // linking with non-static libgcc.
1435   //
1436   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
1437   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
1438   if (TC.getTriple().isAndroid() && LGT != LibGccType::StaticLibGcc)
1439     CmdArgs.push_back("-ldl");
1440 }
1441 
AddRunTimeLibs(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)1442 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1443                            ArgStringList &CmdArgs, const ArgList &Args) {
1444   // Make use of compiler-rt if --rtlib option is used
1445   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1446 
1447   switch (RLT) {
1448   case ToolChain::RLT_CompilerRT:
1449     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1450     AddUnwindLibrary(TC, D, CmdArgs, Args);
1451     break;
1452   case ToolChain::RLT_Libgcc:
1453     // Make sure libgcc is not used under MSVC environment by default
1454     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1455       // Issue error diagnostic if libgcc is explicitly specified
1456       // through command line as --rtlib option argument.
1457       if (Args.hasArg(options::OPT_rtlib_EQ)) {
1458         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1459             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1460       }
1461     } else
1462       AddLibgcc(TC, D, CmdArgs, Args);
1463     break;
1464   }
1465 }
1466 
getStatsFileName(const llvm::opt::ArgList & Args,const InputInfo & Output,const InputInfo & Input,const Driver & D)1467 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1468                                          const InputInfo &Output,
1469                                          const InputInfo &Input,
1470                                          const Driver &D) {
1471   const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1472   if (!A)
1473     return {};
1474 
1475   StringRef SaveStats = A->getValue();
1476   SmallString<128> StatsFile;
1477   if (SaveStats == "obj" && Output.isFilename()) {
1478     StatsFile.assign(Output.getFilename());
1479     llvm::sys::path::remove_filename(StatsFile);
1480   } else if (SaveStats != "cwd") {
1481     D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1482     return {};
1483   }
1484 
1485   StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1486   llvm::sys::path::append(StatsFile, BaseName);
1487   llvm::sys::path::replace_extension(StatsFile, "stats");
1488   return StatsFile;
1489 }
1490 
addMultilibFlag(bool Enabled,const char * const Flag,Multilib::flags_list & Flags)1491 void tools::addMultilibFlag(bool Enabled, const char *const Flag,
1492                             Multilib::flags_list &Flags) {
1493   Flags.push_back(std::string(Enabled ? "+" : "-") + Flag);
1494 }
1495 
addX86AlignBranchArgs(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,bool IsLTO)1496 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
1497                                   ArgStringList &CmdArgs, bool IsLTO) {
1498   auto addArg = [&, IsLTO](const Twine &Arg) {
1499     if (IsLTO) {
1500       CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
1501     } else {
1502       CmdArgs.push_back("-mllvm");
1503       CmdArgs.push_back(Args.MakeArgString(Arg));
1504     }
1505   };
1506 
1507   if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
1508     addArg(Twine("-x86-branches-within-32B-boundaries"));
1509   }
1510   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
1511     StringRef Value = A->getValue();
1512     unsigned Boundary;
1513     if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
1514         !llvm::isPowerOf2_64(Boundary)) {
1515       D.Diag(diag::err_drv_invalid_argument_to_option)
1516           << Value << A->getOption().getName();
1517     } else {
1518       addArg("-x86-align-branch-boundary=" + Twine(Boundary));
1519     }
1520   }
1521   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
1522     std::string AlignBranch;
1523     for (StringRef T : A->getValues()) {
1524       if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
1525           T != "ret" && T != "indirect")
1526         D.Diag(diag::err_drv_invalid_malign_branch_EQ)
1527             << T << "fused, jcc, jmp, call, ret, indirect";
1528       if (!AlignBranch.empty())
1529         AlignBranch += '+';
1530       AlignBranch += T;
1531     }
1532     addArg("-x86-align-branch=" + Twine(AlignBranch));
1533   }
1534   if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
1535     StringRef Value = A->getValue();
1536     unsigned PrefixSize;
1537     if (Value.getAsInteger(10, PrefixSize)) {
1538       D.Diag(diag::err_drv_invalid_argument_to_option)
1539           << Value << A->getOption().getName();
1540     } else {
1541       addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
1542     }
1543   }
1544 }
1545 
getOrCheckAMDGPUCodeObjectVersion(const Driver & D,const llvm::opt::ArgList & Args,bool Diagnose)1546 unsigned tools::getOrCheckAMDGPUCodeObjectVersion(
1547     const Driver &D, const llvm::opt::ArgList &Args, bool Diagnose) {
1548   const unsigned MinCodeObjVer = 2;
1549   const unsigned MaxCodeObjVer = 4;
1550   unsigned CodeObjVer = 4;
1551 
1552   // Emit warnings for legacy options even if they are overridden.
1553   if (Diagnose) {
1554     if (Args.hasArg(options::OPT_mno_code_object_v3_legacy))
1555       D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3"
1556                                             << "-mcode-object-version=2";
1557 
1558     if (Args.hasArg(options::OPT_mcode_object_v3_legacy))
1559       D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3"
1560                                             << "-mcode-object-version=3";
1561   }
1562 
1563   // The last of -mcode-object-v3, -mno-code-object-v3 and
1564   // -mcode-object-version=<version> wins.
1565   if (auto *CodeObjArg =
1566           Args.getLastArg(options::OPT_mcode_object_v3_legacy,
1567                           options::OPT_mno_code_object_v3_legacy,
1568                           options::OPT_mcode_object_version_EQ)) {
1569     if (CodeObjArg->getOption().getID() ==
1570         options::OPT_mno_code_object_v3_legacy) {
1571       CodeObjVer = 2;
1572     } else if (CodeObjArg->getOption().getID() ==
1573                options::OPT_mcode_object_v3_legacy) {
1574       CodeObjVer = 3;
1575     } else {
1576       auto Remnant =
1577           StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
1578       if (Diagnose &&
1579           (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer))
1580         D.Diag(diag::err_drv_invalid_int_value)
1581             << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
1582     }
1583   }
1584   return CodeObjVer;
1585 }
1586