xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/CommonArgs.cpp (revision 5def4c47d4bd90b209b9b4a4ba9faec15846d8fd)
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 
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 
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 
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 
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 
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>
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 
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 
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 
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 
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.
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 
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.
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 
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 
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.
465 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
466   return Triple.getOS() == llvm::Triple::CloudABI;
467 }
468 
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 
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 
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     CmdArgs.push_back("-lomp");
672     break;
673   case Driver::OMPRT_GOMP:
674     CmdArgs.push_back("-lgomp");
675     break;
676   case Driver::OMPRT_IOMP5:
677     CmdArgs.push_back("-liomp5");
678     break;
679   case Driver::OMPRT_Unknown:
680     break;
681   }
682 
683   if (ForceStaticHostRuntime)
684     CmdArgs.push_back("-Bdynamic");
685 
686   if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
687       CmdArgs.push_back("-lrt");
688 
689   if (IsOffloadingHost)
690     CmdArgs.push_back("-lomptarget");
691 
692   addArchSpecificRPath(TC, Args, CmdArgs);
693 
694   return true;
695 }
696 
697 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
698                                 ArgStringList &CmdArgs, StringRef Sanitizer,
699                                 bool IsShared, bool IsWhole) {
700   // Wrap any static runtimes that must be forced into executable in
701   // whole-archive.
702   if (IsWhole) CmdArgs.push_back("--whole-archive");
703   CmdArgs.push_back(TC.getCompilerRTArgString(
704       Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
705   if (IsWhole) CmdArgs.push_back("--no-whole-archive");
706 
707   if (IsShared) {
708     addArchSpecificRPath(TC, Args, CmdArgs);
709   }
710 }
711 
712 // Tries to use a file with the list of dynamic symbols that need to be exported
713 // from the runtime library. Returns true if the file was found.
714 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
715                                     ArgStringList &CmdArgs,
716                                     StringRef Sanitizer) {
717   // Solaris ld defaults to --export-dynamic behaviour but doesn't support
718   // the option, so don't try to pass it.
719   if (TC.getTriple().getOS() == llvm::Triple::Solaris)
720     return true;
721   // Myriad is static linking only.  Furthermore, some versions of its
722   // linker have the bug where --export-dynamic overrides -static, so
723   // don't use --export-dynamic on that platform.
724   if (TC.getTriple().getVendor() == llvm::Triple::Myriad)
725     return true;
726   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
727   if (llvm::sys::fs::exists(SanRT + ".syms")) {
728     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
729     return true;
730   }
731   return false;
732 }
733 
734 static const char *getAsNeededOption(const ToolChain &TC, bool as_needed) {
735   // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
736   // for the native forms -z ignore/-z record, they are missing in Illumos,
737   // so always use the native form.
738   if (TC.getTriple().isOSSolaris())
739     return as_needed ? "-zignore" : "-zrecord";
740   else
741     return as_needed ? "--as-needed" : "--no-as-needed";
742 }
743 
744 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
745                                      ArgStringList &CmdArgs) {
746   // Fuchsia never needs these.  Any sanitizer runtimes with system
747   // dependencies use the `.deplibs` feature instead.
748   if (TC.getTriple().isOSFuchsia())
749     return;
750 
751   // Force linking against the system libraries sanitizers depends on
752   // (see PR15823 why this is necessary).
753   CmdArgs.push_back(getAsNeededOption(TC, false));
754   // There's no libpthread or librt on RTEMS & Android.
755   if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
756       !TC.getTriple().isAndroid()) {
757     CmdArgs.push_back("-lpthread");
758     if (!TC.getTriple().isOSOpenBSD())
759       CmdArgs.push_back("-lrt");
760   }
761   CmdArgs.push_back("-lm");
762   // There's no libdl on all OSes.
763   if (!TC.getTriple().isOSFreeBSD() &&
764       !TC.getTriple().isOSNetBSD() &&
765       !TC.getTriple().isOSOpenBSD() &&
766        TC.getTriple().getOS() != llvm::Triple::RTEMS)
767     CmdArgs.push_back("-ldl");
768   // Required for backtrace on some OSes
769   if (TC.getTriple().isOSFreeBSD() ||
770       TC.getTriple().isOSNetBSD())
771     CmdArgs.push_back("-lexecinfo");
772 }
773 
774 static void
775 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
776                          SmallVectorImpl<StringRef> &SharedRuntimes,
777                          SmallVectorImpl<StringRef> &StaticRuntimes,
778                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
779                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
780                          SmallVectorImpl<StringRef> &RequiredSymbols) {
781   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
782   // Collect shared runtimes.
783   if (SanArgs.needsSharedRt()) {
784     if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
785       SharedRuntimes.push_back("asan");
786       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
787         HelperStaticRuntimes.push_back("asan-preinit");
788     }
789     if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) {
790       SharedRuntimes.push_back("memprof");
791       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
792         HelperStaticRuntimes.push_back("memprof-preinit");
793     }
794     if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
795       if (SanArgs.requiresMinimalRuntime())
796         SharedRuntimes.push_back("ubsan_minimal");
797       else
798         SharedRuntimes.push_back("ubsan_standalone");
799     }
800     if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
801       if (SanArgs.requiresMinimalRuntime())
802         SharedRuntimes.push_back("scudo_minimal");
803       else
804         SharedRuntimes.push_back("scudo");
805     }
806     if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes())
807       SharedRuntimes.push_back("tsan");
808     if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes())
809       SharedRuntimes.push_back("hwasan");
810   }
811 
812   // The stats_client library is also statically linked into DSOs.
813   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
814     StaticRuntimes.push_back("stats_client");
815 
816   // Collect static runtimes.
817   if (Args.hasArg(options::OPT_shared)) {
818     // Don't link static runtimes into DSOs.
819     return;
820   }
821 
822   // Each static runtime that has a DSO counterpart above is excluded below,
823   // but runtimes that exist only as static are not affected by needsSharedRt.
824 
825   if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
826     StaticRuntimes.push_back("asan");
827     if (SanArgs.linkCXXRuntimes())
828       StaticRuntimes.push_back("asan_cxx");
829   }
830 
831   if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt() &&
832       SanArgs.linkRuntimes()) {
833     StaticRuntimes.push_back("memprof");
834     if (SanArgs.linkCXXRuntimes())
835       StaticRuntimes.push_back("memprof_cxx");
836   }
837 
838   if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
839     StaticRuntimes.push_back("hwasan");
840     if (SanArgs.linkCXXRuntimes())
841       StaticRuntimes.push_back("hwasan_cxx");
842   }
843   if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes())
844     StaticRuntimes.push_back("dfsan");
845   if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes())
846     StaticRuntimes.push_back("lsan");
847   if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) {
848     StaticRuntimes.push_back("msan");
849     if (SanArgs.linkCXXRuntimes())
850       StaticRuntimes.push_back("msan_cxx");
851   }
852   if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt() &&
853       SanArgs.linkRuntimes()) {
854     StaticRuntimes.push_back("tsan");
855     if (SanArgs.linkCXXRuntimes())
856       StaticRuntimes.push_back("tsan_cxx");
857   }
858   if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
859     if (SanArgs.requiresMinimalRuntime()) {
860       StaticRuntimes.push_back("ubsan_minimal");
861     } else {
862       StaticRuntimes.push_back("ubsan_standalone");
863       if (SanArgs.linkCXXRuntimes())
864         StaticRuntimes.push_back("ubsan_standalone_cxx");
865     }
866   }
867   if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) {
868     NonWholeStaticRuntimes.push_back("safestack");
869     RequiredSymbols.push_back("__safestack_init");
870   }
871   if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) {
872     if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
873       StaticRuntimes.push_back("cfi");
874     if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) {
875       StaticRuntimes.push_back("cfi_diag");
876       if (SanArgs.linkCXXRuntimes())
877         StaticRuntimes.push_back("ubsan_standalone_cxx");
878     }
879   }
880   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) {
881     NonWholeStaticRuntimes.push_back("stats");
882     RequiredSymbols.push_back("__sanitizer_stats_register");
883   }
884   if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
885     if (SanArgs.requiresMinimalRuntime()) {
886       StaticRuntimes.push_back("scudo_minimal");
887       if (SanArgs.linkCXXRuntimes())
888         StaticRuntimes.push_back("scudo_cxx_minimal");
889     } else {
890       StaticRuntimes.push_back("scudo");
891       if (SanArgs.linkCXXRuntimes())
892         StaticRuntimes.push_back("scudo_cxx");
893     }
894   }
895 }
896 
897 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
898 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
899 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
900                                  ArgStringList &CmdArgs) {
901   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
902       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
903   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
904                            NonWholeStaticRuntimes, HelperStaticRuntimes,
905                            RequiredSymbols);
906 
907   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
908   // Inject libfuzzer dependencies.
909   if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
910       !Args.hasArg(options::OPT_shared)) {
911 
912     addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
913     if (SanArgs.needsFuzzerInterceptors())
914       addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
915                           true);
916     if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
917       bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
918                                  !Args.hasArg(options::OPT_static);
919       if (OnlyLibstdcxxStatic)
920         CmdArgs.push_back("-Bstatic");
921       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
922       if (OnlyLibstdcxxStatic)
923         CmdArgs.push_back("-Bdynamic");
924     }
925   }
926 
927   for (auto RT : SharedRuntimes)
928     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
929   for (auto RT : HelperStaticRuntimes)
930     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
931   bool AddExportDynamic = false;
932   for (auto RT : StaticRuntimes) {
933     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
934     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
935   }
936   for (auto RT : NonWholeStaticRuntimes) {
937     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
938     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
939   }
940   for (auto S : RequiredSymbols) {
941     CmdArgs.push_back("-u");
942     CmdArgs.push_back(Args.MakeArgString(S));
943   }
944   // If there is a static runtime with no dynamic list, force all the symbols
945   // to be dynamic to be sure we export sanitizer interface functions.
946   if (AddExportDynamic)
947     CmdArgs.push_back("--export-dynamic");
948 
949   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
950     CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
951 
952   return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
953 }
954 
955 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
956   if (Args.hasArg(options::OPT_shared))
957     return false;
958 
959   if (TC.getXRayArgs().needsXRayRt()) {
960     CmdArgs.push_back("-whole-archive");
961     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
962     for (const auto &Mode : TC.getXRayArgs().modeList())
963       CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
964     CmdArgs.push_back("-no-whole-archive");
965     return true;
966   }
967 
968   return false;
969 }
970 
971 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
972   CmdArgs.push_back(getAsNeededOption(TC, false));
973   CmdArgs.push_back("-lpthread");
974   if (!TC.getTriple().isOSOpenBSD())
975     CmdArgs.push_back("-lrt");
976   CmdArgs.push_back("-lm");
977 
978   if (!TC.getTriple().isOSFreeBSD() &&
979       !TC.getTriple().isOSNetBSD() &&
980       !TC.getTriple().isOSOpenBSD())
981     CmdArgs.push_back("-ldl");
982 }
983 
984 bool tools::areOptimizationsEnabled(const ArgList &Args) {
985   // Find the last -O arg and see if it is non-zero.
986   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
987     return !A->getOption().matches(options::OPT_O0);
988   // Defaults to -O0.
989   return false;
990 }
991 
992 const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
993                                   const InputInfo &Input,
994                                   const InputInfo &Output) {
995   auto AddPostfix = [JA](auto &F) {
996     if (JA.getOffloadingDeviceKind() == Action::OFK_HIP)
997       F += (Twine("_") + JA.getOffloadingArch()).str();
998     F += ".dwo";
999   };
1000   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
1001     if (StringRef(A->getValue()) == "single")
1002       return Args.MakeArgString(Output.getFilename());
1003 
1004   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
1005   if (FinalOutput && Args.hasArg(options::OPT_c)) {
1006     SmallString<128> T(FinalOutput->getValue());
1007     llvm::sys::path::remove_filename(T);
1008     llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue()));
1009     AddPostfix(T);
1010     return Args.MakeArgString(T);
1011   } else {
1012     // Use the compilation dir.
1013     SmallString<128> T(
1014         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
1015     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
1016     AddPostfix(F);
1017     T += F;
1018     return Args.MakeArgString(F);
1019   }
1020 }
1021 
1022 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
1023                            const JobAction &JA, const ArgList &Args,
1024                            const InputInfo &Output, const char *OutFile) {
1025   ArgStringList ExtractArgs;
1026   ExtractArgs.push_back("--extract-dwo");
1027 
1028   ArgStringList StripArgs;
1029   StripArgs.push_back("--strip-dwo");
1030 
1031   // Grabbing the output of the earlier compile step.
1032   StripArgs.push_back(Output.getFilename());
1033   ExtractArgs.push_back(Output.getFilename());
1034   ExtractArgs.push_back(OutFile);
1035 
1036   const char *Exec =
1037       Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
1038   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1039 
1040   // First extract the dwo sections.
1041   C.addCommand(std::make_unique<Command>(JA, T,
1042                                          ResponseFileSupport::AtFileCurCP(),
1043                                          Exec, ExtractArgs, II, Output));
1044 
1045   // Then remove them from the original .o file.
1046   C.addCommand(std::make_unique<Command>(
1047       JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
1048 }
1049 
1050 // Claim options we don't want to warn if they are unused. We do this for
1051 // options that build systems might add but are unused when assembling or only
1052 // running the preprocessor for example.
1053 void tools::claimNoWarnArgs(const ArgList &Args) {
1054   // Don't warn about unused -f(no-)?lto.  This can happen when we're
1055   // preprocessing, precompiling or assembling.
1056   Args.ClaimAllArgs(options::OPT_flto_EQ);
1057   Args.ClaimAllArgs(options::OPT_flto);
1058   Args.ClaimAllArgs(options::OPT_fno_lto);
1059 }
1060 
1061 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
1062   auto *ProfileUseArg = Args.getLastArg(
1063       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
1064       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
1065       options::OPT_fno_profile_instr_use);
1066 
1067   if (ProfileUseArg &&
1068       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
1069     ProfileUseArg = nullptr;
1070 
1071   return ProfileUseArg;
1072 }
1073 
1074 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
1075   auto *ProfileSampleUseArg = Args.getLastArg(
1076       options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
1077       options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
1078       options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
1079 
1080   if (ProfileSampleUseArg &&
1081       (ProfileSampleUseArg->getOption().matches(
1082            options::OPT_fno_profile_sample_use) ||
1083        ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
1084     return nullptr;
1085 
1086   return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
1087                          options::OPT_fauto_profile_EQ);
1088 }
1089 
1090 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
1091 /// smooshes them together with platform defaults, to decide whether
1092 /// this compile should be using PIC mode or not. Returns a tuple of
1093 /// (RelocationModel, PICLevel, IsPIE).
1094 std::tuple<llvm::Reloc::Model, unsigned, bool>
1095 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
1096   const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
1097   const llvm::Triple &Triple = ToolChain.getTriple();
1098 
1099   bool PIE = ToolChain.isPIEDefault();
1100   bool PIC = PIE || ToolChain.isPICDefault();
1101   // The Darwin/MachO default to use PIC does not apply when using -static.
1102   if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
1103     PIE = PIC = false;
1104   bool IsPICLevelTwo = PIC;
1105 
1106   bool KernelOrKext =
1107       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1108 
1109   // Android-specific defaults for PIC/PIE
1110   if (Triple.isAndroid()) {
1111     switch (Triple.getArch()) {
1112     case llvm::Triple::arm:
1113     case llvm::Triple::armeb:
1114     case llvm::Triple::thumb:
1115     case llvm::Triple::thumbeb:
1116     case llvm::Triple::aarch64:
1117     case llvm::Triple::mips:
1118     case llvm::Triple::mipsel:
1119     case llvm::Triple::mips64:
1120     case llvm::Triple::mips64el:
1121       PIC = true; // "-fpic"
1122       break;
1123 
1124     case llvm::Triple::x86:
1125     case llvm::Triple::x86_64:
1126       PIC = true; // "-fPIC"
1127       IsPICLevelTwo = true;
1128       break;
1129 
1130     default:
1131       break;
1132     }
1133   }
1134 
1135   // OpenBSD-specific defaults for PIE
1136   if (Triple.isOSOpenBSD()) {
1137     switch (ToolChain.getArch()) {
1138     case llvm::Triple::arm:
1139     case llvm::Triple::aarch64:
1140     case llvm::Triple::mips64:
1141     case llvm::Triple::mips64el:
1142     case llvm::Triple::x86:
1143     case llvm::Triple::x86_64:
1144       IsPICLevelTwo = false; // "-fpie"
1145       break;
1146 
1147     case llvm::Triple::ppc:
1148     case llvm::Triple::sparcv9:
1149       IsPICLevelTwo = true; // "-fPIE"
1150       break;
1151 
1152     default:
1153       break;
1154     }
1155   }
1156 
1157   // AMDGPU-specific defaults for PIC.
1158   if (Triple.getArch() == llvm::Triple::amdgcn)
1159     PIC = true;
1160 
1161   // The last argument relating to either PIC or PIE wins, and no
1162   // other argument is used. If the last argument is any flavor of the
1163   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1164   // option implicitly enables PIC at the same level.
1165   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1166                                     options::OPT_fpic, options::OPT_fno_pic,
1167                                     options::OPT_fPIE, options::OPT_fno_PIE,
1168                                     options::OPT_fpie, options::OPT_fno_pie);
1169   if (Triple.isOSWindows() && LastPICArg &&
1170       LastPICArg ==
1171           Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1172                           options::OPT_fPIE, options::OPT_fpie)) {
1173     ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1174         << LastPICArg->getSpelling() << Triple.str();
1175     if (Triple.getArch() == llvm::Triple::x86_64)
1176       return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1177     return std::make_tuple(llvm::Reloc::Static, 0U, false);
1178   }
1179 
1180   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1181   // is forced, then neither PIC nor PIE flags will have no effect.
1182   if (!ToolChain.isPICDefaultForced()) {
1183     if (LastPICArg) {
1184       Option O = LastPICArg->getOption();
1185       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1186           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1187         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1188         PIC =
1189             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1190         IsPICLevelTwo =
1191             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1192       } else {
1193         PIE = PIC = false;
1194         if (EffectiveTriple.isPS4CPU()) {
1195           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1196           StringRef Model = ModelArg ? ModelArg->getValue() : "";
1197           if (Model != "kernel") {
1198             PIC = true;
1199             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
1200                 << LastPICArg->getSpelling();
1201           }
1202         }
1203       }
1204     }
1205   }
1206 
1207   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
1208   // PIC level would've been set to level 1, force it back to level 2 PIC
1209   // instead.
1210   if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
1211     IsPICLevelTwo |= ToolChain.isPICDefault();
1212 
1213   // This kernel flags are a trump-card: they will disable PIC/PIE
1214   // generation, independent of the argument order.
1215   if (KernelOrKext &&
1216       ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1217        !EffectiveTriple.isWatchOS()))
1218     PIC = PIE = false;
1219 
1220   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1221     // This is a very special mode. It trumps the other modes, almost no one
1222     // uses it, and it isn't even valid on any OS but Darwin.
1223     if (!Triple.isOSDarwin())
1224       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1225           << A->getSpelling() << Triple.str();
1226 
1227     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1228 
1229     // Only a forced PIC mode can cause the actual compile to have PIC defines
1230     // etc., no flags are sufficient. This behavior was selected to closely
1231     // match that of llvm-gcc and Apple GCC before that.
1232     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1233 
1234     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1235   }
1236 
1237   bool EmbeddedPISupported;
1238   switch (Triple.getArch()) {
1239     case llvm::Triple::arm:
1240     case llvm::Triple::armeb:
1241     case llvm::Triple::thumb:
1242     case llvm::Triple::thumbeb:
1243       EmbeddedPISupported = true;
1244       break;
1245     default:
1246       EmbeddedPISupported = false;
1247       break;
1248   }
1249 
1250   bool ROPI = false, RWPI = false;
1251   Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1252   if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1253     if (!EmbeddedPISupported)
1254       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1255           << LastROPIArg->getSpelling() << Triple.str();
1256     ROPI = true;
1257   }
1258   Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1259   if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1260     if (!EmbeddedPISupported)
1261       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1262           << LastRWPIArg->getSpelling() << Triple.str();
1263     RWPI = true;
1264   }
1265 
1266   // ROPI and RWPI are not compatible with PIC or PIE.
1267   if ((ROPI || RWPI) && (PIC || PIE))
1268     ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1269 
1270   if (Triple.isMIPS()) {
1271     StringRef CPUName;
1272     StringRef ABIName;
1273     mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1274     // When targeting the N64 ABI, PIC is the default, except in the case
1275     // when the -mno-abicalls option is used. In that case we exit
1276     // at next check regardless of PIC being set below.
1277     if (ABIName == "n64")
1278       PIC = true;
1279     // When targettng MIPS with -mno-abicalls, it's always static.
1280     if(Args.hasArg(options::OPT_mno_abicalls))
1281       return std::make_tuple(llvm::Reloc::Static, 0U, false);
1282     // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1283     // does not use PIC level 2 for historical reasons.
1284     IsPICLevelTwo = false;
1285   }
1286 
1287   if (PIC)
1288     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1289 
1290   llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1291   if (ROPI && RWPI)
1292     RelocM = llvm::Reloc::ROPI_RWPI;
1293   else if (ROPI)
1294     RelocM = llvm::Reloc::ROPI;
1295   else if (RWPI)
1296     RelocM = llvm::Reloc::RWPI;
1297 
1298   return std::make_tuple(RelocM, 0U, false);
1299 }
1300 
1301 // `-falign-functions` indicates that the functions should be aligned to a
1302 // 16-byte boundary.
1303 //
1304 // `-falign-functions=1` is the same as `-fno-align-functions`.
1305 //
1306 // The scalar `n` in `-falign-functions=n` must be an integral value between
1307 // [0, 65536].  If the value is not a power-of-two, it will be rounded up to
1308 // the nearest power-of-two.
1309 //
1310 // If we return `0`, the frontend will default to the backend's preferred
1311 // alignment.
1312 //
1313 // NOTE: icc only allows values between [0, 4096].  icc uses `-falign-functions`
1314 // to mean `-falign-functions=16`.  GCC defaults to the backend's preferred
1315 // alignment.  For unaligned functions, we default to the backend's preferred
1316 // alignment.
1317 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1318                                        const ArgList &Args) {
1319   const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1320                                  options::OPT_falign_functions_EQ,
1321                                  options::OPT_fno_align_functions);
1322   if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1323     return 0;
1324 
1325   if (A->getOption().matches(options::OPT_falign_functions))
1326     return 0;
1327 
1328   unsigned Value = 0;
1329   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1330     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1331         << A->getAsString(Args) << A->getValue();
1332   return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1333 }
1334 
1335 unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC,
1336                                          const ArgList &Args) {
1337   const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
1338 
1339   if (!A)
1340     return 0;
1341 
1342   unsigned Value = 0;
1343   if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
1344       Value < 2)
1345     TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1346         << A->getAsString(Args) << A->getValue();
1347   return Value;
1348 }
1349 
1350 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1351                              ArgStringList &CmdArgs) {
1352   llvm::Reloc::Model RelocationModel;
1353   unsigned PICLevel;
1354   bool IsPIE;
1355   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1356 
1357   if (RelocationModel != llvm::Reloc::Static)
1358     CmdArgs.push_back("-KPIC");
1359 }
1360 
1361 /// Determine whether Objective-C automated reference counting is
1362 /// enabled.
1363 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1364   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1365 }
1366 
1367 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
1368 
1369 static LibGccType getLibGccType(const Driver &D, const ArgList &Args) {
1370   if (Args.hasArg(options::OPT_static_libgcc) ||
1371       Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie))
1372     return LibGccType::StaticLibGcc;
1373   if (Args.hasArg(options::OPT_shared_libgcc) || D.CCCIsCXX())
1374     return LibGccType::SharedLibGcc;
1375   return LibGccType::UnspecifiedLibGcc;
1376 }
1377 
1378 // Gcc adds libgcc arguments in various ways:
1379 //
1380 // gcc <none>:     -lgcc --as-needed -lgcc_s --no-as-needed
1381 // g++ <none>:                       -lgcc_s               -lgcc
1382 // gcc shared:                       -lgcc_s               -lgcc
1383 // g++ shared:                       -lgcc_s               -lgcc
1384 // gcc static:     -lgcc             -lgcc_eh
1385 // g++ static:     -lgcc             -lgcc_eh
1386 // gcc static-pie: -lgcc             -lgcc_eh
1387 // g++ static-pie: -lgcc             -lgcc_eh
1388 //
1389 // Also, certain targets need additional adjustments.
1390 
1391 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
1392                              ArgStringList &CmdArgs, const ArgList &Args) {
1393   ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
1394   // Targets that don't use unwind libraries.
1395   if (TC.getTriple().isAndroid() || TC.getTriple().isOSIAMCU() ||
1396       TC.getTriple().isOSBinFormatWasm() ||
1397       UNW == ToolChain::UNW_None)
1398     return;
1399 
1400   LibGccType LGT = getLibGccType(D, Args);
1401   bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
1402                   !TC.getTriple().isAndroid() && !TC.getTriple().isOSCygMing();
1403   if (AsNeeded)
1404     CmdArgs.push_back(getAsNeededOption(TC, true));
1405 
1406   switch (UNW) {
1407   case ToolChain::UNW_None:
1408     return;
1409   case ToolChain::UNW_Libgcc: {
1410     if (LGT == LibGccType::StaticLibGcc)
1411       CmdArgs.push_back("-lgcc_eh");
1412     else
1413       CmdArgs.push_back("-lgcc_s");
1414     break;
1415   }
1416   case ToolChain::UNW_CompilerRT:
1417     if (LGT == LibGccType::StaticLibGcc)
1418       CmdArgs.push_back("-l:libunwind.a");
1419     else if (TC.getTriple().isOSCygMing()) {
1420       if (LGT == LibGccType::SharedLibGcc)
1421         CmdArgs.push_back("-l:libunwind.dll.a");
1422       else
1423         // Let the linker choose between libunwind.dll.a and libunwind.a
1424         // depending on what's available, and depending on the -static flag
1425         CmdArgs.push_back("-lunwind");
1426     } else
1427       CmdArgs.push_back("-l:libunwind.so");
1428     break;
1429   }
1430 
1431   if (AsNeeded)
1432     CmdArgs.push_back(getAsNeededOption(TC, false));
1433 }
1434 
1435 static void AddLibgcc(const ToolChain &TC, const Driver &D,
1436                       ArgStringList &CmdArgs, const ArgList &Args) {
1437   LibGccType LGT = getLibGccType(D, Args);
1438   if (LGT != LibGccType::SharedLibGcc)
1439     CmdArgs.push_back("-lgcc");
1440   AddUnwindLibrary(TC, D, CmdArgs, Args);
1441   if (LGT == LibGccType::SharedLibGcc)
1442     CmdArgs.push_back("-lgcc");
1443 
1444   // According to Android ABI, we have to link with libdl if we are
1445   // linking with non-static libgcc.
1446   //
1447   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
1448   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
1449   if (TC.getTriple().isAndroid() && LGT != LibGccType::StaticLibGcc)
1450     CmdArgs.push_back("-ldl");
1451 }
1452 
1453 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1454                            ArgStringList &CmdArgs, const ArgList &Args) {
1455   // Make use of compiler-rt if --rtlib option is used
1456   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1457 
1458   switch (RLT) {
1459   case ToolChain::RLT_CompilerRT:
1460     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1461     AddUnwindLibrary(TC, D, CmdArgs, Args);
1462     break;
1463   case ToolChain::RLT_Libgcc:
1464     // Make sure libgcc is not used under MSVC environment by default
1465     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1466       // Issue error diagnostic if libgcc is explicitly specified
1467       // through command line as --rtlib option argument.
1468       if (Args.hasArg(options::OPT_rtlib_EQ)) {
1469         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1470             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1471       }
1472     } else
1473       AddLibgcc(TC, D, CmdArgs, Args);
1474     break;
1475   }
1476 }
1477 
1478 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1479                                          const InputInfo &Output,
1480                                          const InputInfo &Input,
1481                                          const Driver &D) {
1482   const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1483   if (!A)
1484     return {};
1485 
1486   StringRef SaveStats = A->getValue();
1487   SmallString<128> StatsFile;
1488   if (SaveStats == "obj" && Output.isFilename()) {
1489     StatsFile.assign(Output.getFilename());
1490     llvm::sys::path::remove_filename(StatsFile);
1491   } else if (SaveStats != "cwd") {
1492     D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1493     return {};
1494   }
1495 
1496   StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1497   llvm::sys::path::append(StatsFile, BaseName);
1498   llvm::sys::path::replace_extension(StatsFile, "stats");
1499   return StatsFile;
1500 }
1501 
1502 void tools::addMultilibFlag(bool Enabled, const char *const Flag,
1503                             Multilib::flags_list &Flags) {
1504   Flags.push_back(std::string(Enabled ? "+" : "-") + Flag);
1505 }
1506 
1507 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
1508                                   ArgStringList &CmdArgs, bool IsLTO) {
1509   auto addArg = [&, IsLTO](const Twine &Arg) {
1510     if (IsLTO) {
1511       CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
1512     } else {
1513       CmdArgs.push_back("-mllvm");
1514       CmdArgs.push_back(Args.MakeArgString(Arg));
1515     }
1516   };
1517 
1518   if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
1519     addArg(Twine("-x86-branches-within-32B-boundaries"));
1520   }
1521   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
1522     StringRef Value = A->getValue();
1523     unsigned Boundary;
1524     if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
1525         !llvm::isPowerOf2_64(Boundary)) {
1526       D.Diag(diag::err_drv_invalid_argument_to_option)
1527           << Value << A->getOption().getName();
1528     } else {
1529       addArg("-x86-align-branch-boundary=" + Twine(Boundary));
1530     }
1531   }
1532   if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
1533     std::string AlignBranch;
1534     for (StringRef T : A->getValues()) {
1535       if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
1536           T != "ret" && T != "indirect")
1537         D.Diag(diag::err_drv_invalid_malign_branch_EQ)
1538             << T << "fused, jcc, jmp, call, ret, indirect";
1539       if (!AlignBranch.empty())
1540         AlignBranch += '+';
1541       AlignBranch += T;
1542     }
1543     addArg("-x86-align-branch=" + Twine(AlignBranch));
1544   }
1545   if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
1546     StringRef Value = A->getValue();
1547     unsigned PrefixSize;
1548     if (Value.getAsInteger(10, PrefixSize)) {
1549       D.Diag(diag::err_drv_invalid_argument_to_option)
1550           << Value << A->getOption().getName();
1551     } else {
1552       addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
1553     }
1554   }
1555 }
1556 
1557 unsigned tools::getOrCheckAMDGPUCodeObjectVersion(
1558     const Driver &D, const llvm::opt::ArgList &Args, bool Diagnose) {
1559   const unsigned MinCodeObjVer = 2;
1560   const unsigned MaxCodeObjVer = 4;
1561   unsigned CodeObjVer = 3;
1562 
1563   // Emit warnings for legacy options even if they are overridden.
1564   if (Diagnose) {
1565     if (Args.hasArg(options::OPT_mno_code_object_v3_legacy))
1566       D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3"
1567                                             << "-mcode-object-version=2";
1568 
1569     if (Args.hasArg(options::OPT_mcode_object_v3_legacy))
1570       D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3"
1571                                             << "-mcode-object-version=3";
1572   }
1573 
1574   // The last of -mcode-object-v3, -mno-code-object-v3 and
1575   // -mcode-object-version=<version> wins.
1576   if (auto *CodeObjArg =
1577           Args.getLastArg(options::OPT_mcode_object_v3_legacy,
1578                           options::OPT_mno_code_object_v3_legacy,
1579                           options::OPT_mcode_object_version_EQ)) {
1580     if (CodeObjArg->getOption().getID() ==
1581         options::OPT_mno_code_object_v3_legacy) {
1582       CodeObjVer = 2;
1583     } else if (CodeObjArg->getOption().getID() ==
1584                options::OPT_mcode_object_v3_legacy) {
1585       CodeObjVer = 3;
1586     } else {
1587       auto Remnant =
1588           StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
1589       if (Diagnose &&
1590           (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer))
1591         D.Diag(diag::err_drv_invalid_int_value)
1592             << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
1593     }
1594   }
1595   return CodeObjVer;
1596 }
1597 
1598 void tools::addMachineOutlinerArgs(const Driver &D,
1599                                    const llvm::opt::ArgList &Args,
1600                                    llvm::opt::ArgStringList &CmdArgs,
1601                                    const llvm::Triple &Triple, bool IsLTO) {
1602   auto addArg = [&, IsLTO](const Twine &Arg) {
1603     if (IsLTO) {
1604       CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
1605     } else {
1606       CmdArgs.push_back("-mllvm");
1607       CmdArgs.push_back(Args.MakeArgString(Arg));
1608     }
1609   };
1610 
1611   if (Arg *A = Args.getLastArg(options::OPT_moutline,
1612                                options::OPT_mno_outline)) {
1613     if (A->getOption().matches(options::OPT_moutline)) {
1614       // We only support -moutline in AArch64 and ARM targets right now. If
1615       // we're not compiling for these, emit a warning and ignore the flag.
1616       // Otherwise, add the proper mllvm flags.
1617       if (!(Triple.isARM() || Triple.isThumb() ||
1618             Triple.getArch() == llvm::Triple::aarch64 ||
1619             Triple.getArch() == llvm::Triple::aarch64_32)) {
1620         D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
1621       } else {
1622         addArg(Twine("-enable-machine-outliner"));
1623       }
1624     } else {
1625       // Disable all outlining behaviour.
1626       addArg(Twine("-enable-machine-outliner=never"));
1627     }
1628   }
1629 }
1630