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