xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp (revision e64bea71c21eb42e97aa615188ba91f6cce0d36d)
1 //===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- 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 "Clang.h"
10 #include "Arch/ARM.h"
11 #include "Arch/LoongArch.h"
12 #include "Arch/Mips.h"
13 #include "Arch/PPC.h"
14 #include "Arch/RISCV.h"
15 #include "Arch/Sparc.h"
16 #include "Arch/SystemZ.h"
17 #include "Hexagon.h"
18 #include "PS4CPU.h"
19 #include "clang/Basic/CLWarnings.h"
20 #include "clang/Basic/CodeGenOptions.h"
21 #include "clang/Basic/HeaderInclude.h"
22 #include "clang/Basic/LangOptions.h"
23 #include "clang/Basic/MakeSupport.h"
24 #include "clang/Basic/ObjCRuntime.h"
25 #include "clang/Basic/Version.h"
26 #include "clang/Config/config.h"
27 #include "clang/Driver/Action.h"
28 #include "clang/Driver/CommonArgs.h"
29 #include "clang/Driver/Distro.h"
30 #include "clang/Driver/InputInfo.h"
31 #include "clang/Driver/Options.h"
32 #include "clang/Driver/SanitizerArgs.h"
33 #include "clang/Driver/Types.h"
34 #include "clang/Driver/XRayArgs.h"
35 #include "llvm/ADT/ScopeExit.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/BinaryFormat/Magic.h"
39 #include "llvm/Config/llvm-config.h"
40 #include "llvm/Frontend/Debug/Options.h"
41 #include "llvm/Object/ObjectFile.h"
42 #include "llvm/Option/ArgList.h"
43 #include "llvm/Support/CodeGen.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/Compression.h"
46 #include "llvm/Support/Error.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/Path.h"
49 #include "llvm/Support/Process.h"
50 #include "llvm/Support/YAMLParser.h"
51 #include "llvm/TargetParser/AArch64TargetParser.h"
52 #include "llvm/TargetParser/ARMTargetParserCommon.h"
53 #include "llvm/TargetParser/Host.h"
54 #include "llvm/TargetParser/LoongArchTargetParser.h"
55 #include "llvm/TargetParser/PPCTargetParser.h"
56 #include "llvm/TargetParser/RISCVISAInfo.h"
57 #include "llvm/TargetParser/RISCVTargetParser.h"
58 #include <cctype>
59 
60 using namespace clang::driver;
61 using namespace clang::driver::tools;
62 using namespace clang;
63 using namespace llvm::opt;
64 
CheckPreprocessingOptions(const Driver & D,const ArgList & Args)65 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
66   if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
67                                options::OPT_fminimize_whitespace,
68                                options::OPT_fno_minimize_whitespace,
69                                options::OPT_fkeep_system_includes,
70                                options::OPT_fno_keep_system_includes)) {
71     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
72         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
73       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
74           << A->getBaseArg().getAsString(Args)
75           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
76     }
77   }
78 }
79 
CheckCodeGenerationOptions(const Driver & D,const ArgList & Args)80 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
81   // In gcc, only ARM checks this, but it seems reasonable to check universally.
82   if (Args.hasArg(options::OPT_static))
83     if (const Arg *A =
84             Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
85       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
86                                                       << "-static";
87 }
88 
89 /// Apply \a Work on the current tool chain \a RegularToolChain and any other
90 /// offloading tool chain that is associated with the current action \a JA.
91 static void
forAllAssociatedToolChains(Compilation & C,const JobAction & JA,const ToolChain & RegularToolChain,llvm::function_ref<void (const ToolChain &)> Work)92 forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
93                            const ToolChain &RegularToolChain,
94                            llvm::function_ref<void(const ToolChain &)> Work) {
95   // Apply Work on the current/regular tool chain.
96   Work(RegularToolChain);
97 
98   // Apply Work on all the offloading tool chains associated with the current
99   // action.
100   if (JA.isHostOffloading(Action::OFK_Cuda))
101     Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
102   else if (JA.isDeviceOffloading(Action::OFK_Cuda))
103     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
104   else if (JA.isHostOffloading(Action::OFK_HIP))
105     Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
106   else if (JA.isDeviceOffloading(Action::OFK_HIP))
107     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
108 
109   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
110     auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
111     for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
112       Work(*II->second);
113   } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
114     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
115 
116   if (JA.isHostOffloading(Action::OFK_SYCL)) {
117     auto TCs = C.getOffloadToolChains<Action::OFK_SYCL>();
118     for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
119       Work(*II->second);
120   } else if (JA.isDeviceOffloading(Action::OFK_SYCL))
121     Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
122 
123   //
124   // TODO: Add support for other offloading programming models here.
125   //
126 }
127 
128 static bool
shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime & runtime,const llvm::Triple & Triple)129 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
130                                           const llvm::Triple &Triple) {
131   // We use the zero-cost exception tables for Objective-C if the non-fragile
132   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
133   // later.
134   if (runtime.isNonFragile())
135     return true;
136 
137   if (!Triple.isMacOSX())
138     return false;
139 
140   return (!Triple.isMacOSXVersionLT(10, 5) &&
141           (Triple.getArch() == llvm::Triple::x86_64 ||
142            Triple.getArch() == llvm::Triple::arm));
143 }
144 
145 /// Adds exception related arguments to the driver command arguments. There's a
146 /// main flag, -fexceptions and also language specific flags to enable/disable
147 /// C++ and Objective-C exceptions. This makes it possible to for example
148 /// disable C++ exceptions but enable Objective-C exceptions.
addExceptionArgs(const ArgList & Args,types::ID InputType,const ToolChain & TC,bool KernelOrKext,const ObjCRuntime & objcRuntime,ArgStringList & CmdArgs)149 static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
150                              const ToolChain &TC, bool KernelOrKext,
151                              const ObjCRuntime &objcRuntime,
152                              ArgStringList &CmdArgs) {
153   const llvm::Triple &Triple = TC.getTriple();
154 
155   if (KernelOrKext) {
156     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
157     // arguments now to avoid warnings about unused arguments.
158     Args.ClaimAllArgs(options::OPT_fexceptions);
159     Args.ClaimAllArgs(options::OPT_fno_exceptions);
160     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
161     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
162     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
163     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
164     Args.ClaimAllArgs(options::OPT_fasync_exceptions);
165     Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
166     return false;
167   }
168 
169   // See if the user explicitly enabled exceptions.
170   bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
171                          false);
172 
173   // Async exceptions are Windows MSVC only.
174   if (Triple.isWindowsMSVCEnvironment()) {
175     bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
176                             options::OPT_fno_async_exceptions, false);
177     if (EHa) {
178       CmdArgs.push_back("-fasync-exceptions");
179       EH = true;
180     }
181   }
182 
183   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
184   // is not necessarily sensible, but follows GCC.
185   if (types::isObjC(InputType) &&
186       Args.hasFlag(options::OPT_fobjc_exceptions,
187                    options::OPT_fno_objc_exceptions, true)) {
188     CmdArgs.push_back("-fobjc-exceptions");
189 
190     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
191   }
192 
193   if (types::isCXX(InputType)) {
194     // Disable C++ EH by default on XCore and PS4/PS5.
195     bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
196                                 !Triple.isPS() && !Triple.isDriverKit();
197     Arg *ExceptionArg = Args.getLastArg(
198         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
199         options::OPT_fexceptions, options::OPT_fno_exceptions);
200     if (ExceptionArg)
201       CXXExceptionsEnabled =
202           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
203           ExceptionArg->getOption().matches(options::OPT_fexceptions);
204 
205     if (CXXExceptionsEnabled) {
206       CmdArgs.push_back("-fcxx-exceptions");
207 
208       EH = true;
209     }
210   }
211 
212   // OPT_fignore_exceptions means exception could still be thrown,
213   // but no clean up or catch would happen in current module.
214   // So we do not set EH to false.
215   Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
216 
217   Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
218                     options::OPT_fno_assume_nothrow_exception_dtor);
219 
220   if (EH)
221     CmdArgs.push_back("-fexceptions");
222   return EH;
223 }
224 
ShouldEnableAutolink(const ArgList & Args,const ToolChain & TC,const JobAction & JA)225 static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
226                                  const JobAction &JA) {
227   bool Default = true;
228   if (TC.getTriple().isOSDarwin()) {
229     // The native darwin assembler doesn't support the linker_option directives,
230     // so we disable them if we think the .s file will be passed to it.
231     Default = TC.useIntegratedAs();
232   }
233   // The linker_option directives are intended for host compilation.
234   if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
235       JA.isDeviceOffloading(Action::OFK_HIP))
236     Default = false;
237   return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
238                       Default);
239 }
240 
241 /// Add a CC1 option to specify the debug compilation directory.
addDebugCompDirArg(const ArgList & Args,ArgStringList & CmdArgs,const llvm::vfs::FileSystem & VFS)242 static const char *addDebugCompDirArg(const ArgList &Args,
243                                       ArgStringList &CmdArgs,
244                                       const llvm::vfs::FileSystem &VFS) {
245   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
246                                options::OPT_fdebug_compilation_dir_EQ)) {
247     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
248       CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
249                                            A->getValue()));
250     else
251       A->render(Args, CmdArgs);
252   } else if (llvm::ErrorOr<std::string> CWD =
253                  VFS.getCurrentWorkingDirectory()) {
254     CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
255   }
256   StringRef Path(CmdArgs.back());
257   return Path.substr(Path.find('=') + 1).data();
258 }
259 
addDebugObjectName(const ArgList & Args,ArgStringList & CmdArgs,const char * DebugCompilationDir,const char * OutputFileName)260 static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
261                                const char *DebugCompilationDir,
262                                const char *OutputFileName) {
263   // No need to generate a value for -object-file-name if it was provided.
264   for (auto *Arg : Args.filtered(options::OPT_Xclang))
265     if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
266       return;
267 
268   if (Args.hasArg(options::OPT_object_file_name_EQ))
269     return;
270 
271   SmallString<128> ObjFileNameForDebug(OutputFileName);
272   if (ObjFileNameForDebug != "-" &&
273       !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
274       (!DebugCompilationDir ||
275        llvm::sys::path::is_absolute(DebugCompilationDir))) {
276     // Make the path absolute in the debug infos like MSVC does.
277     llvm::sys::fs::make_absolute(ObjFileNameForDebug);
278   }
279   // If the object file name is a relative path, then always use Windows
280   // backslash style as -object-file-name is used for embedding object file path
281   // in codeview and it can only be generated when targeting on Windows.
282   // Otherwise, just use native absolute path.
283   llvm::sys::path::Style Style =
284       llvm::sys::path::is_absolute(ObjFileNameForDebug)
285           ? llvm::sys::path::Style::native
286           : llvm::sys::path::Style::windows_backslash;
287   llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
288                                Style);
289   CmdArgs.push_back(
290       Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
291 }
292 
293 /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
addDebugPrefixMapArg(const Driver & D,const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)294 static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
295                                  const ArgList &Args, ArgStringList &CmdArgs) {
296   auto AddOneArg = [&](StringRef Map, StringRef Name) {
297     if (!Map.contains('='))
298       D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
299     else
300       CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
301   };
302 
303   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
304                                     options::OPT_fdebug_prefix_map_EQ)) {
305     AddOneArg(A->getValue(), A->getOption().getName());
306     A->claim();
307   }
308   std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
309   if (GlobalRemapEntry.empty())
310     return;
311   AddOneArg(GlobalRemapEntry, "environment");
312 }
313 
314 /// Add a CC1 and CC1AS option to specify the macro file path prefix map.
addMacroPrefixMapArg(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)315 static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
316                                  ArgStringList &CmdArgs) {
317   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
318                                     options::OPT_fmacro_prefix_map_EQ)) {
319     StringRef Map = A->getValue();
320     if (!Map.contains('='))
321       D.Diag(diag::err_drv_invalid_argument_to_option)
322           << Map << A->getOption().getName();
323     else
324       CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
325     A->claim();
326   }
327 }
328 
329 /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
addCoveragePrefixMapArg(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)330 static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
331                                    ArgStringList &CmdArgs) {
332   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
333                                     options::OPT_fcoverage_prefix_map_EQ)) {
334     StringRef Map = A->getValue();
335     if (!Map.contains('='))
336       D.Diag(diag::err_drv_invalid_argument_to_option)
337           << Map << A->getOption().getName();
338     else
339       CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
340     A->claim();
341   }
342 }
343 
344 /// Add -x lang to \p CmdArgs for \p Input.
addDashXForInput(const ArgList & Args,const InputInfo & Input,ArgStringList & CmdArgs)345 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
346                              ArgStringList &CmdArgs) {
347   // When using -verify-pch, we don't want to provide the type
348   // 'precompiled-header' if it was inferred from the file extension
349   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
350     return;
351 
352   CmdArgs.push_back("-x");
353   if (Args.hasArg(options::OPT_rewrite_objc))
354     CmdArgs.push_back(types::getTypeName(types::TY_ObjCXX));
355   else {
356     // Map the driver type to the frontend type. This is mostly an identity
357     // mapping, except that the distinction between module interface units
358     // and other source files does not exist at the frontend layer.
359     const char *ClangType;
360     switch (Input.getType()) {
361     case types::TY_CXXModule:
362       ClangType = "c++";
363       break;
364     case types::TY_PP_CXXModule:
365       ClangType = "c++-cpp-output";
366       break;
367     default:
368       ClangType = types::getTypeName(Input.getType());
369       break;
370     }
371     CmdArgs.push_back(ClangType);
372   }
373 }
374 
addPGOAndCoverageFlags(const ToolChain & TC,Compilation & C,const JobAction & JA,const InputInfo & Output,const ArgList & Args,SanitizerArgs & SanArgs,ArgStringList & CmdArgs)375 static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
376                                    const JobAction &JA, const InputInfo &Output,
377                                    const ArgList &Args, SanitizerArgs &SanArgs,
378                                    ArgStringList &CmdArgs) {
379   const Driver &D = TC.getDriver();
380   const llvm::Triple &T = TC.getTriple();
381   auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
382                                          options::OPT_fprofile_generate_EQ,
383                                          options::OPT_fno_profile_generate);
384   if (PGOGenerateArg &&
385       PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
386     PGOGenerateArg = nullptr;
387 
388   auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
389 
390   auto *ProfileGenerateArg = Args.getLastArg(
391       options::OPT_fprofile_instr_generate,
392       options::OPT_fprofile_instr_generate_EQ,
393       options::OPT_fno_profile_instr_generate);
394   if (ProfileGenerateArg &&
395       ProfileGenerateArg->getOption().matches(
396           options::OPT_fno_profile_instr_generate))
397     ProfileGenerateArg = nullptr;
398 
399   if (PGOGenerateArg && ProfileGenerateArg)
400     D.Diag(diag::err_drv_argument_not_allowed_with)
401         << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
402 
403   auto *ProfileUseArg = getLastProfileUseArg(Args);
404 
405   if (PGOGenerateArg && ProfileUseArg)
406     D.Diag(diag::err_drv_argument_not_allowed_with)
407         << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
408 
409   if (ProfileGenerateArg && ProfileUseArg)
410     D.Diag(diag::err_drv_argument_not_allowed_with)
411         << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
412 
413   if (CSPGOGenerateArg && PGOGenerateArg) {
414     D.Diag(diag::err_drv_argument_not_allowed_with)
415         << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
416     PGOGenerateArg = nullptr;
417   }
418 
419   if (TC.getTriple().isOSAIX()) {
420     if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
421       D.Diag(diag::err_drv_unsupported_opt_for_target)
422           << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
423   }
424 
425   if (ProfileGenerateArg) {
426     if (ProfileGenerateArg->getOption().matches(
427             options::OPT_fprofile_instr_generate_EQ))
428       CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
429                                            ProfileGenerateArg->getValue()));
430     // The default is to use Clang Instrumentation.
431     CmdArgs.push_back("-fprofile-instrument=clang");
432     if (TC.getTriple().isWindowsMSVCEnvironment() &&
433         Args.hasFlag(options::OPT_frtlib_defaultlib,
434                      options::OPT_fno_rtlib_defaultlib, true)) {
435       // Add dependent lib for clang_rt.profile
436       CmdArgs.push_back(Args.MakeArgString(
437           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
438     }
439   }
440 
441   if (auto *ColdFuncCoverageArg = Args.getLastArg(
442           options::OPT_fprofile_generate_cold_function_coverage,
443           options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
444     SmallString<128> Path(
445         ColdFuncCoverageArg->getOption().matches(
446             options::OPT_fprofile_generate_cold_function_coverage_EQ)
447             ? ColdFuncCoverageArg->getValue()
448             : "");
449     llvm::sys::path::append(Path, "default_%m.profraw");
450     // FIXME: Idealy the file path should be passed through
451     // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
452     // shared with other profile use path(see PGOOptions), we need to refactor
453     // PGOOptions to make it work.
454     CmdArgs.push_back("-mllvm");
455     CmdArgs.push_back(Args.MakeArgString(
456         Twine("--instrument-cold-function-only-path=") + Path));
457     CmdArgs.push_back("-mllvm");
458     CmdArgs.push_back("--pgo-instrument-cold-function-only");
459     CmdArgs.push_back("-mllvm");
460     CmdArgs.push_back("--pgo-function-entry-coverage");
461     CmdArgs.push_back("-fprofile-instrument=sample-coldcov");
462   }
463 
464   if (auto *A = Args.getLastArg(options::OPT_ftemporal_profile)) {
465     if (!PGOGenerateArg && !CSPGOGenerateArg)
466       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
467           << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
468     CmdArgs.push_back("-mllvm");
469     CmdArgs.push_back("--pgo-temporal-instrumentation");
470   }
471 
472   Arg *PGOGenArg = nullptr;
473   if (PGOGenerateArg) {
474     assert(!CSPGOGenerateArg);
475     PGOGenArg = PGOGenerateArg;
476     CmdArgs.push_back("-fprofile-instrument=llvm");
477   }
478   if (CSPGOGenerateArg) {
479     assert(!PGOGenerateArg);
480     PGOGenArg = CSPGOGenerateArg;
481     CmdArgs.push_back("-fprofile-instrument=csllvm");
482   }
483   if (PGOGenArg) {
484     if (TC.getTriple().isWindowsMSVCEnvironment() &&
485         Args.hasFlag(options::OPT_frtlib_defaultlib,
486                      options::OPT_fno_rtlib_defaultlib, true)) {
487       // Add dependent lib for clang_rt.profile
488       CmdArgs.push_back(Args.MakeArgString(
489           "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
490     }
491     if (PGOGenArg->getOption().matches(
492             PGOGenerateArg ? options::OPT_fprofile_generate_EQ
493                            : options::OPT_fcs_profile_generate_EQ)) {
494       SmallString<128> Path(PGOGenArg->getValue());
495       llvm::sys::path::append(Path, "default_%m.profraw");
496       CmdArgs.push_back(
497           Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
498     }
499   }
500 
501   if (ProfileUseArg) {
502     if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
503       CmdArgs.push_back(Args.MakeArgString(
504           Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
505     else if ((ProfileUseArg->getOption().matches(
506                   options::OPT_fprofile_use_EQ) ||
507               ProfileUseArg->getOption().matches(
508                   options::OPT_fprofile_instr_use))) {
509       SmallString<128> Path(
510           ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
511       if (Path.empty() || llvm::sys::fs::is_directory(Path))
512         llvm::sys::path::append(Path, "default.profdata");
513       CmdArgs.push_back(
514           Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
515     }
516   }
517 
518   bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
519                                    options::OPT_fno_test_coverage, false) ||
520                       Args.hasArg(options::OPT_coverage);
521   bool EmitCovData = TC.needsGCovInstrumentation(Args);
522 
523   if (Args.hasFlag(options::OPT_fcoverage_mapping,
524                    options::OPT_fno_coverage_mapping, false)) {
525     if (!ProfileGenerateArg)
526       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
527           << "-fcoverage-mapping"
528           << "-fprofile-instr-generate";
529 
530     CmdArgs.push_back("-fcoverage-mapping");
531   }
532 
533   if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
534                    false)) {
535     if (!Args.hasFlag(options::OPT_fcoverage_mapping,
536                       options::OPT_fno_coverage_mapping, false))
537       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
538           << "-fcoverage-mcdc"
539           << "-fcoverage-mapping";
540 
541     CmdArgs.push_back("-fcoverage-mcdc");
542   }
543 
544   if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
545                                options::OPT_fcoverage_compilation_dir_EQ)) {
546     if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
547       CmdArgs.push_back(Args.MakeArgString(
548           Twine("-fcoverage-compilation-dir=") + A->getValue()));
549     else
550       A->render(Args, CmdArgs);
551   } else if (llvm::ErrorOr<std::string> CWD =
552                  D.getVFS().getCurrentWorkingDirectory()) {
553     CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
554   }
555 
556   if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
557     auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
558     if (!Args.hasArg(options::OPT_coverage))
559       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
560           << "-fprofile-exclude-files="
561           << "--coverage";
562 
563     StringRef v = Arg->getValue();
564     CmdArgs.push_back(
565         Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
566   }
567 
568   if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
569     auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
570     if (!Args.hasArg(options::OPT_coverage))
571       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
572           << "-fprofile-filter-files="
573           << "--coverage";
574 
575     StringRef v = Arg->getValue();
576     CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
577   }
578 
579   if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
580     StringRef Val = A->getValue();
581     if (Val == "atomic" || Val == "prefer-atomic")
582       CmdArgs.push_back("-fprofile-update=atomic");
583     else if (Val != "single")
584       D.Diag(diag::err_drv_unsupported_option_argument)
585           << A->getSpelling() << Val;
586   }
587   if (const auto *A = Args.getLastArg(options::OPT_fprofile_continuous)) {
588     if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
589       D.Diag(clang::diag::err_drv_argument_only_allowed_with)
590           << A->getSpelling()
591           << "-fprofile-generate, -fprofile-instr-generate, or "
592              "-fcs-profile-generate";
593     else {
594       CmdArgs.push_back("-fprofile-continuous");
595       // Platforms that require a bias variable:
596       if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
597         CmdArgs.push_back("-mllvm");
598         CmdArgs.push_back("-runtime-counter-relocation");
599       }
600       // -fprofile-instr-generate does not decide the profile file name in the
601       // FE, and so it does not define the filename symbol
602       // (__llvm_profile_filename). Instead, the runtime uses the name
603       // "default.profraw" for the profile file. When continuous mode is ON, we
604       // will create the filename symbol so that we can insert the "%c"
605       // modifier.
606       if (ProfileGenerateArg &&
607           (ProfileGenerateArg->getOption().matches(
608                options::OPT_fprofile_instr_generate) ||
609            (ProfileGenerateArg->getOption().matches(
610                 options::OPT_fprofile_instr_generate_EQ) &&
611             strlen(ProfileGenerateArg->getValue()) == 0)))
612         CmdArgs.push_back("-fprofile-instrument-path=default.profraw");
613     }
614   }
615 
616   int FunctionGroups = 1;
617   int SelectedFunctionGroup = 0;
618   if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
619     StringRef Val = A->getValue();
620     if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
621       D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
622   }
623   if (const auto *A =
624           Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
625     StringRef Val = A->getValue();
626     if (Val.getAsInteger(0, SelectedFunctionGroup) ||
627         SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
628       D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
629   }
630   if (FunctionGroups != 1)
631     CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
632                                          Twine(FunctionGroups)));
633   if (SelectedFunctionGroup != 0)
634     CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
635                                          Twine(SelectedFunctionGroup)));
636 
637   // Leave -fprofile-dir= an unused argument unless .gcda emission is
638   // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
639   // the flag used. There is no -fno-profile-dir, so the user has no
640   // targeted way to suppress the warning.
641   Arg *FProfileDir = nullptr;
642   if (Args.hasArg(options::OPT_fprofile_arcs) ||
643       Args.hasArg(options::OPT_coverage))
644     FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
645 
646   // Put the .gcno and .gcda files (if needed) next to the primary output file,
647   // or fall back to a file in the current directory for `clang -c --coverage
648   // d/a.c` in the absence of -o.
649   if (EmitCovNotes || EmitCovData) {
650     SmallString<128> CoverageFilename;
651     if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
652       // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
653       // path separator.
654       CoverageFilename = DumpDir->getValue();
655       CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
656     } else if (Arg *FinalOutput =
657                    C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
658       CoverageFilename = FinalOutput->getValue();
659     } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
660       CoverageFilename = FinalOutput->getValue();
661     } else {
662       CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
663     }
664     if (llvm::sys::path::is_relative(CoverageFilename))
665       (void)D.getVFS().makeAbsolute(CoverageFilename);
666     llvm::sys::path::replace_extension(CoverageFilename, "gcno");
667     if (EmitCovNotes) {
668       CmdArgs.push_back(
669           Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
670     }
671 
672     if (EmitCovData) {
673       if (FProfileDir) {
674         SmallString<128> Gcno = std::move(CoverageFilename);
675         CoverageFilename = FProfileDir->getValue();
676         llvm::sys::path::append(CoverageFilename, Gcno);
677       }
678       llvm::sys::path::replace_extension(CoverageFilename, "gcda");
679       CmdArgs.push_back(
680           Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
681     }
682   }
683 }
684 
685 static void
RenderDebugEnablingArgs(const ArgList & Args,ArgStringList & CmdArgs,llvm::codegenoptions::DebugInfoKind DebugInfoKind,unsigned DwarfVersion,llvm::DebuggerKind DebuggerTuning)686 RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
687                         llvm::codegenoptions::DebugInfoKind DebugInfoKind,
688                         unsigned DwarfVersion,
689                         llvm::DebuggerKind DebuggerTuning) {
690   addDebugInfoKind(CmdArgs, DebugInfoKind);
691   if (DwarfVersion > 0)
692     CmdArgs.push_back(
693         Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
694   switch (DebuggerTuning) {
695   case llvm::DebuggerKind::GDB:
696     CmdArgs.push_back("-debugger-tuning=gdb");
697     break;
698   case llvm::DebuggerKind::LLDB:
699     CmdArgs.push_back("-debugger-tuning=lldb");
700     break;
701   case llvm::DebuggerKind::SCE:
702     CmdArgs.push_back("-debugger-tuning=sce");
703     break;
704   case llvm::DebuggerKind::DBX:
705     CmdArgs.push_back("-debugger-tuning=dbx");
706     break;
707   default:
708     break;
709   }
710 }
711 
checkDebugInfoOption(const Arg * A,const ArgList & Args,const Driver & D,const ToolChain & TC)712 static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
713                                  const Driver &D, const ToolChain &TC) {
714   assert(A && "Expected non-nullptr argument.");
715   if (TC.supportsDebugInfoOption(A))
716     return true;
717   D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
718       << A->getAsString(Args) << TC.getTripleString();
719   return false;
720 }
721 
RenderDebugInfoCompressionArgs(const ArgList & Args,ArgStringList & CmdArgs,const Driver & D,const ToolChain & TC)722 static void RenderDebugInfoCompressionArgs(const ArgList &Args,
723                                            ArgStringList &CmdArgs,
724                                            const Driver &D,
725                                            const ToolChain &TC) {
726   const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
727   if (!A)
728     return;
729   if (checkDebugInfoOption(A, Args, D, TC)) {
730     StringRef Value = A->getValue();
731     if (Value == "none") {
732       CmdArgs.push_back("--compress-debug-sections=none");
733     } else if (Value == "zlib") {
734       if (llvm::compression::zlib::isAvailable()) {
735         CmdArgs.push_back(
736             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
737       } else {
738         D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
739       }
740     } else if (Value == "zstd") {
741       if (llvm::compression::zstd::isAvailable()) {
742         CmdArgs.push_back(
743             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
744       } else {
745         D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
746       }
747     } else {
748       D.Diag(diag::err_drv_unsupported_option_argument)
749           << A->getSpelling() << Value;
750     }
751   }
752 }
753 
handleAMDGPUCodeObjectVersionOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,bool IsCC1As=false)754 static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
755                                                  const ArgList &Args,
756                                                  ArgStringList &CmdArgs,
757                                                  bool IsCC1As = false) {
758   // If no version was requested by the user, use the default value from the
759   // back end. This is consistent with the value returned from
760   // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
761   // requiring the corresponding llvm to have the AMDGPU target enabled,
762   // provided the user (e.g. front end tests) can use the default.
763   if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
764     unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
765     CmdArgs.insert(CmdArgs.begin() + 1,
766                    Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
767                                       Twine(CodeObjVer)));
768     CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
769     // -cc1as does not accept -mcode-object-version option.
770     if (!IsCC1As)
771       CmdArgs.insert(CmdArgs.begin() + 1,
772                      Args.MakeArgString(Twine("-mcode-object-version=") +
773                                         Twine(CodeObjVer)));
774   }
775 }
776 
maybeHasClangPchSignature(const Driver & D,StringRef Path)777 static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
778   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
779       D.getVFS().getBufferForFile(Path);
780   if (!MemBuf)
781     return false;
782   llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
783   if (Magic == llvm::file_magic::unknown)
784     return false;
785   // Return true for both raw Clang AST files and object files which may
786   // contain a __clangast section.
787   if (Magic == llvm::file_magic::clang_ast)
788     return true;
789   Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =
790       llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
791   return !Obj.takeError();
792 }
793 
gchProbe(const Driver & D,StringRef Path)794 static bool gchProbe(const Driver &D, StringRef Path) {
795   llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
796   if (!Status)
797     return false;
798 
799   if (Status->isDirectory()) {
800     std::error_code EC;
801     for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
802          !EC && DI != DE; DI = DI.increment(EC)) {
803       if (maybeHasClangPchSignature(D, DI->path()))
804         return true;
805     }
806     D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
807     return false;
808   }
809 
810   if (maybeHasClangPchSignature(D, Path))
811     return true;
812   D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
813   return false;
814 }
815 
AddPreprocessingOptions(Compilation & C,const JobAction & JA,const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfoList & Inputs) const816 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
817                                     const Driver &D, const ArgList &Args,
818                                     ArgStringList &CmdArgs,
819                                     const InputInfo &Output,
820                                     const InputInfoList &Inputs) const {
821   const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
822 
823   CheckPreprocessingOptions(D, Args);
824 
825   Args.AddLastArg(CmdArgs, options::OPT_C);
826   Args.AddLastArg(CmdArgs, options::OPT_CC);
827 
828   // Handle dependency file generation.
829   Arg *ArgM = Args.getLastArg(options::OPT_MM);
830   if (!ArgM)
831     ArgM = Args.getLastArg(options::OPT_M);
832   Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
833   if (!ArgMD)
834     ArgMD = Args.getLastArg(options::OPT_MD);
835 
836   // -M and -MM imply -w.
837   if (ArgM)
838     CmdArgs.push_back("-w");
839   else
840     ArgM = ArgMD;
841 
842   if (ArgM) {
843     if (!JA.isDeviceOffloading(Action::OFK_HIP)) {
844       // Determine the output location.
845       const char *DepFile;
846       if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
847         DepFile = MF->getValue();
848         C.addFailureResultFile(DepFile, &JA);
849       } else if (Output.getType() == types::TY_Dependencies) {
850         DepFile = Output.getFilename();
851       } else if (!ArgMD) {
852         DepFile = "-";
853       } else {
854         DepFile = getDependencyFileName(Args, Inputs);
855         C.addFailureResultFile(DepFile, &JA);
856       }
857       CmdArgs.push_back("-dependency-file");
858       CmdArgs.push_back(DepFile);
859     }
860     // Cmake generates dependency files using all compilation options specified
861     // by users. Claim those not used for dependency files.
862     if (JA.isOffloading(Action::OFK_HIP)) {
863       Args.ClaimAllArgs(options::OPT_offload_compress);
864       Args.ClaimAllArgs(options::OPT_no_offload_compress);
865       Args.ClaimAllArgs(options::OPT_offload_jobs_EQ);
866     }
867 
868     bool HasTarget = false;
869     for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
870       HasTarget = true;
871       A->claim();
872       if (A->getOption().matches(options::OPT_MT)) {
873         A->render(Args, CmdArgs);
874       } else {
875         CmdArgs.push_back("-MT");
876         SmallString<128> Quoted;
877         quoteMakeTarget(A->getValue(), Quoted);
878         CmdArgs.push_back(Args.MakeArgString(Quoted));
879       }
880     }
881 
882     // Add a default target if one wasn't specified.
883     if (!HasTarget) {
884       const char *DepTarget;
885 
886       // If user provided -o, that is the dependency target, except
887       // when we are only generating a dependency file.
888       Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
889       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
890         DepTarget = OutputOpt->getValue();
891       } else {
892         // Otherwise derive from the base input.
893         //
894         // FIXME: This should use the computed output file location.
895         SmallString<128> P(Inputs[0].getBaseInput());
896         llvm::sys::path::replace_extension(P, "o");
897         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
898       }
899 
900       CmdArgs.push_back("-MT");
901       SmallString<128> Quoted;
902       quoteMakeTarget(DepTarget, Quoted);
903       CmdArgs.push_back(Args.MakeArgString(Quoted));
904     }
905 
906     if (ArgM->getOption().matches(options::OPT_M) ||
907         ArgM->getOption().matches(options::OPT_MD))
908       CmdArgs.push_back("-sys-header-deps");
909     if ((isa<PrecompileJobAction>(JA) &&
910          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
911         Args.hasArg(options::OPT_fmodule_file_deps))
912       CmdArgs.push_back("-module-file-deps");
913   }
914 
915   if (Args.hasArg(options::OPT_MG)) {
916     if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
917         ArgM->getOption().matches(options::OPT_MMD))
918       D.Diag(diag::err_drv_mg_requires_m_or_mm);
919     CmdArgs.push_back("-MG");
920   }
921 
922   Args.AddLastArg(CmdArgs, options::OPT_MP);
923   Args.AddLastArg(CmdArgs, options::OPT_MV);
924 
925   // Add offload include arguments specific for CUDA/HIP/SYCL. This must happen
926   // before we -I or -include anything else, because we must pick up the
927   // CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL installation,
928   // rather than from e.g. /usr/local/include.
929   if (JA.isOffloading(Action::OFK_Cuda))
930     getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
931   if (JA.isOffloading(Action::OFK_HIP))
932     getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
933   if (JA.isOffloading(Action::OFK_SYCL))
934     getToolChain().addSYCLIncludeArgs(Args, CmdArgs);
935 
936   // If we are offloading to a target via OpenMP we need to include the
937   // openmp_wrappers folder which contains alternative system headers.
938   if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
939       !Args.hasArg(options::OPT_nostdinc) &&
940       Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
941                    true) &&
942       getToolChain().getTriple().isGPU()) {
943     if (!Args.hasArg(options::OPT_nobuiltininc)) {
944       // Add openmp_wrappers/* to our system include path.  This lets us wrap
945       // standard library headers.
946       SmallString<128> P(D.ResourceDir);
947       llvm::sys::path::append(P, "include");
948       llvm::sys::path::append(P, "openmp_wrappers");
949       CmdArgs.push_back("-internal-isystem");
950       CmdArgs.push_back(Args.MakeArgString(P));
951     }
952 
953     CmdArgs.push_back("-include");
954     CmdArgs.push_back("__clang_openmp_device_functions.h");
955   }
956 
957   if (Args.hasArg(options::OPT_foffload_via_llvm)) {
958     // Add llvm_wrappers/* to our system include path.  This lets us wrap
959     // standard library headers and other headers.
960     SmallString<128> P(D.ResourceDir);
961     llvm::sys::path::append(P, "include", "llvm_offload_wrappers");
962     CmdArgs.append({"-internal-isystem", Args.MakeArgString(P), "-include"});
963     if (JA.isDeviceOffloading(Action::OFK_OpenMP))
964       CmdArgs.push_back("__llvm_offload_device.h");
965     else
966       CmdArgs.push_back("__llvm_offload_host.h");
967   }
968 
969   // Add -i* options, and automatically translate to
970   // -include-pch/-include-pth for transparent PCH support. It's
971   // wonky, but we include looking for .gch so we can support seamless
972   // replacement into a build system already set up to be generating
973   // .gch files.
974 
975   if (getToolChain().getDriver().IsCLMode()) {
976     const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
977     const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
978     if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
979         JA.getKind() <= Action::AssembleJobClass) {
980       CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
981       // -fpch-instantiate-templates is the default when creating
982       // precomp using /Yc
983       if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
984                        options::OPT_fno_pch_instantiate_templates, true))
985         CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
986     }
987     if (YcArg || YuArg) {
988       StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
989       if (!isa<PrecompileJobAction>(JA)) {
990         CmdArgs.push_back("-include-pch");
991         CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
992             C, !ThroughHeader.empty()
993                    ? ThroughHeader
994                    : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
995       }
996 
997       if (ThroughHeader.empty()) {
998         CmdArgs.push_back(Args.MakeArgString(
999             Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1000       } else {
1001         CmdArgs.push_back(
1002             Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1003       }
1004     }
1005   }
1006 
1007   bool RenderedImplicitInclude = false;
1008   for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1009     if (A->getOption().matches(options::OPT_include) &&
1010         D.getProbePrecompiled()) {
1011       // Handling of gcc-style gch precompiled headers.
1012       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1013       RenderedImplicitInclude = true;
1014 
1015       bool FoundPCH = false;
1016       SmallString<128> P(A->getValue());
1017       // We want the files to have a name like foo.h.pch. Add a dummy extension
1018       // so that replace_extension does the right thing.
1019       P += ".dummy";
1020       llvm::sys::path::replace_extension(P, "pch");
1021       if (D.getVFS().exists(P))
1022         FoundPCH = true;
1023 
1024       if (!FoundPCH) {
1025         // For GCC compat, probe for a file or directory ending in .gch instead.
1026         llvm::sys::path::replace_extension(P, "gch");
1027         FoundPCH = gchProbe(D, P.str());
1028       }
1029 
1030       if (FoundPCH) {
1031         if (IsFirstImplicitInclude) {
1032           A->claim();
1033           CmdArgs.push_back("-include-pch");
1034           CmdArgs.push_back(Args.MakeArgString(P));
1035           continue;
1036         } else {
1037           // Ignore the PCH if not first on command line and emit warning.
1038           D.Diag(diag::warn_drv_pch_not_first_include) << P
1039                                                        << A->getAsString(Args);
1040         }
1041       }
1042     } else if (A->getOption().matches(options::OPT_isystem_after)) {
1043       // Handling of paths which must come late.  These entries are handled by
1044       // the toolchain itself after the resource dir is inserted in the right
1045       // search order.
1046       // Do not claim the argument so that the use of the argument does not
1047       // silently go unnoticed on toolchains which do not honour the option.
1048       continue;
1049     } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1050       // Translated to -internal-isystem by the driver, no need to pass to cc1.
1051       continue;
1052     } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1053       // This is used only by the driver. No need to pass to cc1.
1054       continue;
1055     }
1056 
1057     // Not translated, render as usual.
1058     A->claim();
1059     A->render(Args, CmdArgs);
1060   }
1061 
1062   Args.addAllArgs(CmdArgs,
1063                   {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1064                    options::OPT_F, options::OPT_embed_dir_EQ});
1065 
1066   // Add -Wp, and -Xpreprocessor if using the preprocessor.
1067 
1068   // FIXME: There is a very unfortunate problem here, some troubled
1069   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1070   // really support that we would have to parse and then translate
1071   // those options. :(
1072   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1073                        options::OPT_Xpreprocessor);
1074 
1075   // -I- is a deprecated GCC feature, reject it.
1076   if (Arg *A = Args.getLastArg(options::OPT_I_))
1077     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1078 
1079   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1080   // -isysroot to the CC1 invocation.
1081   StringRef sysroot = C.getSysRoot();
1082   if (sysroot != "") {
1083     if (!Args.hasArg(options::OPT_isysroot)) {
1084       CmdArgs.push_back("-isysroot");
1085       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1086     }
1087   }
1088 
1089   // Parse additional include paths from environment variables.
1090   // FIXME: We should probably sink the logic for handling these from the
1091   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1092   // CPATH - included following the user specified includes (but prior to
1093   // builtin and standard includes).
1094   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1095   // C_INCLUDE_PATH - system includes enabled when compiling C.
1096   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1097   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1098   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1099   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1100   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1101   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1102   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1103 
1104   // While adding the include arguments, we also attempt to retrieve the
1105   // arguments of related offloading toolchains or arguments that are specific
1106   // of an offloading programming model.
1107 
1108   // Add C++ include arguments, if needed.
1109   if (types::isCXX(Inputs[0].getType())) {
1110     bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1111     forAllAssociatedToolChains(
1112         C, JA, getToolChain(),
1113         [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1114           HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1115                              : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1116         });
1117   }
1118 
1119   // If we are compiling for a GPU target we want to override the system headers
1120   // with ones created by the 'libc' project if present.
1121   // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1122   //       OffloadKind as an argument.
1123   if (!Args.hasArg(options::OPT_nostdinc) &&
1124       Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
1125                    true) &&
1126       !Args.hasArg(options::OPT_nobuiltininc)) {
1127     // Without an offloading language we will include these headers directly.
1128     // Offloading languages will instead only use the declarations stored in
1129     // the resource directory at clang/lib/Headers/llvm_libc_wrappers.
1130     if (getToolChain().getTriple().isGPU() &&
1131         C.getActiveOffloadKinds() == Action::OFK_None) {
1132       SmallString<128> P(llvm::sys::path::parent_path(D.Dir));
1133       llvm::sys::path::append(P, "include");
1134       llvm::sys::path::append(P, getToolChain().getTripleString());
1135       CmdArgs.push_back("-internal-isystem");
1136       CmdArgs.push_back(Args.MakeArgString(P));
1137     } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
1138       // TODO: CUDA / HIP include their own headers for some common functions
1139       // implemented here. We'll need to clean those up so they do not conflict.
1140       SmallString<128> P(D.ResourceDir);
1141       llvm::sys::path::append(P, "include");
1142       llvm::sys::path::append(P, "llvm_libc_wrappers");
1143       CmdArgs.push_back("-internal-isystem");
1144       CmdArgs.push_back(Args.MakeArgString(P));
1145     }
1146   }
1147 
1148   // Add system include arguments for all targets but IAMCU.
1149   if (!IsIAMCU)
1150     forAllAssociatedToolChains(C, JA, getToolChain(),
1151                                [&Args, &CmdArgs](const ToolChain &TC) {
1152                                  TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1153                                });
1154   else {
1155     // For IAMCU add special include arguments.
1156     getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1157   }
1158 
1159   addMacroPrefixMapArg(D, Args, CmdArgs);
1160   addCoveragePrefixMapArg(D, Args, CmdArgs);
1161 
1162   Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1163                   options::OPT_fno_file_reproducible);
1164 
1165   if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1166     CmdArgs.push_back("-source-date-epoch");
1167     CmdArgs.push_back(Args.MakeArgString(Epoch));
1168   }
1169 
1170   Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1171                     options::OPT_fno_define_target_os_macros);
1172 }
1173 
1174 // FIXME: Move to target hook.
isSignedCharDefault(const llvm::Triple & Triple)1175 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1176   switch (Triple.getArch()) {
1177   default:
1178     return true;
1179 
1180   case llvm::Triple::aarch64:
1181   case llvm::Triple::aarch64_32:
1182   case llvm::Triple::aarch64_be:
1183   case llvm::Triple::arm:
1184   case llvm::Triple::armeb:
1185   case llvm::Triple::thumb:
1186   case llvm::Triple::thumbeb:
1187     if (Triple.isOSDarwin() || Triple.isOSWindows())
1188       return true;
1189     return false;
1190 
1191   case llvm::Triple::ppc:
1192   case llvm::Triple::ppc64:
1193     if (Triple.isOSDarwin())
1194       return true;
1195     return false;
1196 
1197   case llvm::Triple::csky:
1198   case llvm::Triple::hexagon:
1199   case llvm::Triple::msp430:
1200   case llvm::Triple::ppcle:
1201   case llvm::Triple::ppc64le:
1202   case llvm::Triple::riscv32:
1203   case llvm::Triple::riscv64:
1204   case llvm::Triple::systemz:
1205   case llvm::Triple::xcore:
1206   case llvm::Triple::xtensa:
1207     return false;
1208   }
1209 }
1210 
hasMultipleInvocations(const llvm::Triple & Triple,const ArgList & Args)1211 static bool hasMultipleInvocations(const llvm::Triple &Triple,
1212                                    const ArgList &Args) {
1213   // Supported only on Darwin where we invoke the compiler multiple times
1214   // followed by an invocation to lipo.
1215   if (!Triple.isOSDarwin())
1216     return false;
1217   // If more than one "-arch <arch>" is specified, we're targeting multiple
1218   // architectures resulting in a fat binary.
1219   return Args.getAllArgValues(options::OPT_arch).size() > 1;
1220 }
1221 
checkRemarksOptions(const Driver & D,const ArgList & Args,const llvm::Triple & Triple)1222 static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1223                                 const llvm::Triple &Triple) {
1224   // When enabling remarks, we need to error if:
1225   // * The remark file is specified but we're targeting multiple architectures,
1226   // which means more than one remark file is being generated.
1227   bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1228   bool hasExplicitOutputFile =
1229       Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1230   if (hasMultipleInvocations && hasExplicitOutputFile) {
1231     D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1232         << "-foptimization-record-file";
1233     return false;
1234   }
1235   return true;
1236 }
1237 
renderRemarksOptions(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple,const InputInfo & Input,const InputInfo & Output,const JobAction & JA)1238 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1239                                  const llvm::Triple &Triple,
1240                                  const InputInfo &Input,
1241                                  const InputInfo &Output, const JobAction &JA) {
1242   StringRef Format = "yaml";
1243   if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1244     Format = A->getValue();
1245 
1246   CmdArgs.push_back("-opt-record-file");
1247 
1248   const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1249   if (A) {
1250     CmdArgs.push_back(A->getValue());
1251   } else {
1252     bool hasMultipleArchs =
1253         Triple.isOSDarwin() && // Only supported on Darwin platforms.
1254         Args.getAllArgValues(options::OPT_arch).size() > 1;
1255 
1256     SmallString<128> F;
1257 
1258     if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1259       if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1260         F = FinalOutput->getValue();
1261     } else {
1262       if (Format != "yaml" && // For YAML, keep the original behavior.
1263           Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1264           Output.isFilename())
1265         F = Output.getFilename();
1266     }
1267 
1268     if (F.empty()) {
1269       // Use the input filename.
1270       F = llvm::sys::path::stem(Input.getBaseInput());
1271 
1272       // If we're compiling for an offload architecture (i.e. a CUDA device),
1273       // we need to make the file name for the device compilation different
1274       // from the host compilation.
1275       if (!JA.isDeviceOffloading(Action::OFK_None) &&
1276           !JA.isDeviceOffloading(Action::OFK_Host)) {
1277         llvm::sys::path::replace_extension(F, "");
1278         F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1279                                                  Triple.normalize());
1280         F += "-";
1281         F += JA.getOffloadingArch();
1282       }
1283     }
1284 
1285     // If we're having more than one "-arch", we should name the files
1286     // differently so that every cc1 invocation writes to a different file.
1287     // We're doing that by appending "-<arch>" with "<arch>" being the arch
1288     // name from the triple.
1289     if (hasMultipleArchs) {
1290       // First, remember the extension.
1291       SmallString<64> OldExtension = llvm::sys::path::extension(F);
1292       // then, remove it.
1293       llvm::sys::path::replace_extension(F, "");
1294       // attach -<arch> to it.
1295       F += "-";
1296       F += Triple.getArchName();
1297       // put back the extension.
1298       llvm::sys::path::replace_extension(F, OldExtension);
1299     }
1300 
1301     SmallString<32> Extension;
1302     Extension += "opt.";
1303     Extension += Format;
1304 
1305     llvm::sys::path::replace_extension(F, Extension);
1306     CmdArgs.push_back(Args.MakeArgString(F));
1307   }
1308 
1309   if (const Arg *A =
1310           Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1311     CmdArgs.push_back("-opt-record-passes");
1312     CmdArgs.push_back(A->getValue());
1313   }
1314 
1315   if (!Format.empty()) {
1316     CmdArgs.push_back("-opt-record-format");
1317     CmdArgs.push_back(Format.data());
1318   }
1319 }
1320 
AddAAPCSVolatileBitfieldArgs(const ArgList & Args,ArgStringList & CmdArgs)1321 void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1322   if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1323                     options::OPT_fno_aapcs_bitfield_width, true))
1324     CmdArgs.push_back("-fno-aapcs-bitfield-width");
1325 
1326   if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1327     CmdArgs.push_back("-faapcs-bitfield-load");
1328 }
1329 
1330 namespace {
RenderARMABI(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs)1331 void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1332                   const ArgList &Args, ArgStringList &CmdArgs) {
1333   // Select the ABI to use.
1334   // FIXME: Support -meabi.
1335   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1336   const char *ABIName = nullptr;
1337   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1338     ABIName = A->getValue();
1339   } else {
1340     std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
1341     ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1342   }
1343 
1344   CmdArgs.push_back("-target-abi");
1345   CmdArgs.push_back(ABIName);
1346 }
1347 
AddUnalignedAccessWarning(ArgStringList & CmdArgs)1348 void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1349   auto StrictAlignIter =
1350       llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1351         return Arg == "+strict-align" || Arg == "-strict-align";
1352       });
1353   if (StrictAlignIter != CmdArgs.rend() &&
1354       StringRef(*StrictAlignIter) == "+strict-align")
1355     CmdArgs.push_back("-Wunaligned-access");
1356 }
1357 }
1358 
1359 // Each combination of options here forms a signing schema, and in most cases
1360 // each signing schema is its own incompatible ABI. The default values of the
1361 // options represent the default signing schema.
handlePAuthABI(const ArgList & DriverArgs,ArgStringList & CC1Args)1362 static void handlePAuthABI(const ArgList &DriverArgs, ArgStringList &CC1Args) {
1363   if (!DriverArgs.hasArg(options::OPT_fptrauth_intrinsics,
1364                          options::OPT_fno_ptrauth_intrinsics))
1365     CC1Args.push_back("-fptrauth-intrinsics");
1366 
1367   if (!DriverArgs.hasArg(options::OPT_fptrauth_calls,
1368                          options::OPT_fno_ptrauth_calls))
1369     CC1Args.push_back("-fptrauth-calls");
1370 
1371   if (!DriverArgs.hasArg(options::OPT_fptrauth_returns,
1372                          options::OPT_fno_ptrauth_returns))
1373     CC1Args.push_back("-fptrauth-returns");
1374 
1375   if (!DriverArgs.hasArg(options::OPT_fptrauth_auth_traps,
1376                          options::OPT_fno_ptrauth_auth_traps))
1377     CC1Args.push_back("-fptrauth-auth-traps");
1378 
1379   if (!DriverArgs.hasArg(
1380           options::OPT_fptrauth_vtable_pointer_address_discrimination,
1381           options::OPT_fno_ptrauth_vtable_pointer_address_discrimination))
1382     CC1Args.push_back("-fptrauth-vtable-pointer-address-discrimination");
1383 
1384   if (!DriverArgs.hasArg(
1385           options::OPT_fptrauth_vtable_pointer_type_discrimination,
1386           options::OPT_fno_ptrauth_vtable_pointer_type_discrimination))
1387     CC1Args.push_back("-fptrauth-vtable-pointer-type-discrimination");
1388 
1389   if (!DriverArgs.hasArg(options::OPT_fptrauth_indirect_gotos,
1390                          options::OPT_fno_ptrauth_indirect_gotos))
1391     CC1Args.push_back("-fptrauth-indirect-gotos");
1392 
1393   if (!DriverArgs.hasArg(options::OPT_fptrauth_init_fini,
1394                          options::OPT_fno_ptrauth_init_fini))
1395     CC1Args.push_back("-fptrauth-init-fini");
1396 }
1397 
CollectARMPACBTIOptions(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,bool isAArch64)1398 static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1399                                     ArgStringList &CmdArgs, bool isAArch64) {
1400   const llvm::Triple &Triple = TC.getEffectiveTriple();
1401   const Arg *A = isAArch64
1402                      ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1403                                        options::OPT_mbranch_protection_EQ)
1404                      : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1405   if (!A) {
1406     if (Triple.isOSOpenBSD() && isAArch64) {
1407       CmdArgs.push_back("-msign-return-address=non-leaf");
1408       CmdArgs.push_back("-msign-return-address-key=a_key");
1409       CmdArgs.push_back("-mbranch-target-enforce");
1410     }
1411     return;
1412   }
1413 
1414   const Driver &D = TC.getDriver();
1415   if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1416     D.Diag(diag::warn_incompatible_branch_protection_option)
1417         << Triple.getArchName();
1418 
1419   StringRef Scope, Key;
1420   bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1421 
1422   if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1423     Scope = A->getValue();
1424     if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1425       D.Diag(diag::err_drv_unsupported_option_argument)
1426           << A->getSpelling() << Scope;
1427     Key = "a_key";
1428     IndirectBranches = Triple.isOSOpenBSD() && isAArch64;
1429     BranchProtectionPAuthLR = false;
1430     GuardedControlStack = false;
1431   } else {
1432     StringRef DiagMsg;
1433     llvm::ARM::ParsedBranchProtection PBP;
1434     bool EnablePAuthLR = false;
1435 
1436     // To know if we need to enable PAuth-LR As part of the standard branch
1437     // protection option, it needs to be determined if the feature has been
1438     // activated in the `march` argument. This information is stored within the
1439     // CmdArgs variable and can be found using a search.
1440     if (isAArch64) {
1441       auto isPAuthLR = [](const char *member) {
1442         llvm::AArch64::ExtensionInfo pauthlr_extension =
1443             llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1444         return pauthlr_extension.PosTargetFeature == member;
1445       };
1446 
1447       if (llvm::any_of(CmdArgs, isPAuthLR))
1448         EnablePAuthLR = true;
1449     }
1450     if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg,
1451                                           EnablePAuthLR))
1452       D.Diag(diag::err_drv_unsupported_option_argument)
1453           << A->getSpelling() << DiagMsg;
1454     if (!isAArch64 && PBP.Key == "b_key")
1455       D.Diag(diag::warn_unsupported_branch_protection)
1456           << "b-key" << A->getAsString(Args);
1457     Scope = PBP.Scope;
1458     Key = PBP.Key;
1459     BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1460     IndirectBranches = PBP.BranchTargetEnforcement;
1461     GuardedControlStack = PBP.GuardedControlStack;
1462   }
1463 
1464   bool HasPtrauthReturns = llvm::any_of(CmdArgs, [](const char *Arg) {
1465     return StringRef(Arg) == "-fptrauth-returns";
1466   });
1467   // GCS is currently untested with ptrauth-returns, but enabling this could be
1468   // allowed in future after testing with a suitable system.
1469   if (HasPtrauthReturns &&
1470       (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack)) {
1471     if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1472       D.Diag(diag::err_drv_unsupported_opt_for_target)
1473           << A->getAsString(Args) << Triple.getTriple();
1474     else
1475       D.Diag(diag::err_drv_incompatible_options)
1476           << A->getAsString(Args) << "-fptrauth-returns";
1477   }
1478 
1479   CmdArgs.push_back(
1480       Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1481   if (Scope != "none")
1482     CmdArgs.push_back(
1483         Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1484   if (BranchProtectionPAuthLR)
1485     CmdArgs.push_back(
1486         Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1487   if (IndirectBranches)
1488     CmdArgs.push_back("-mbranch-target-enforce");
1489 
1490   if (GuardedControlStack)
1491     CmdArgs.push_back("-mguarded-control-stack");
1492 }
1493 
AddARMTargetArgs(const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext) const1494 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1495                              ArgStringList &CmdArgs, bool KernelOrKext) const {
1496   RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1497 
1498   // Determine floating point ABI from the options & target defaults.
1499   arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1500   if (ABI == arm::FloatABI::Soft) {
1501     // Floating point operations and argument passing are soft.
1502     // FIXME: This changes CPP defines, we need -target-soft-float.
1503     CmdArgs.push_back("-msoft-float");
1504     CmdArgs.push_back("-mfloat-abi");
1505     CmdArgs.push_back("soft");
1506   } else if (ABI == arm::FloatABI::SoftFP) {
1507     // Floating point operations are hard, but argument passing is soft.
1508     CmdArgs.push_back("-mfloat-abi");
1509     CmdArgs.push_back("soft");
1510   } else {
1511     // Floating point operations and argument passing are hard.
1512     assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1513     CmdArgs.push_back("-mfloat-abi");
1514     CmdArgs.push_back("hard");
1515   }
1516 
1517   // Forward the -mglobal-merge option for explicit control over the pass.
1518   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1519                                options::OPT_mno_global_merge)) {
1520     CmdArgs.push_back("-mllvm");
1521     if (A->getOption().matches(options::OPT_mno_global_merge))
1522       CmdArgs.push_back("-arm-global-merge=false");
1523     else
1524       CmdArgs.push_back("-arm-global-merge=true");
1525   }
1526 
1527   if (!Args.hasFlag(options::OPT_mimplicit_float,
1528                     options::OPT_mno_implicit_float, true))
1529     CmdArgs.push_back("-no-implicit-float");
1530 
1531   if (Args.getLastArg(options::OPT_mcmse))
1532     CmdArgs.push_back("-mcmse");
1533 
1534   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1535 
1536   // Enable/disable return address signing and indirect branch targets.
1537   CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1538 
1539   AddUnalignedAccessWarning(CmdArgs);
1540 }
1541 
RenderTargetOptions(const llvm::Triple & EffectiveTriple,const ArgList & Args,bool KernelOrKext,ArgStringList & CmdArgs) const1542 void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1543                                 const ArgList &Args, bool KernelOrKext,
1544                                 ArgStringList &CmdArgs) const {
1545   const ToolChain &TC = getToolChain();
1546 
1547   // Add the target features
1548   getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1549 
1550   // Add target specific flags.
1551   switch (TC.getArch()) {
1552   default:
1553     break;
1554 
1555   case llvm::Triple::arm:
1556   case llvm::Triple::armeb:
1557   case llvm::Triple::thumb:
1558   case llvm::Triple::thumbeb:
1559     // Use the effective triple, which takes into account the deployment target.
1560     AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1561     break;
1562 
1563   case llvm::Triple::aarch64:
1564   case llvm::Triple::aarch64_32:
1565   case llvm::Triple::aarch64_be:
1566     AddAArch64TargetArgs(Args, CmdArgs);
1567     break;
1568 
1569   case llvm::Triple::loongarch32:
1570   case llvm::Triple::loongarch64:
1571     AddLoongArchTargetArgs(Args, CmdArgs);
1572     break;
1573 
1574   case llvm::Triple::mips:
1575   case llvm::Triple::mipsel:
1576   case llvm::Triple::mips64:
1577   case llvm::Triple::mips64el:
1578     AddMIPSTargetArgs(Args, CmdArgs);
1579     break;
1580 
1581   case llvm::Triple::ppc:
1582   case llvm::Triple::ppcle:
1583   case llvm::Triple::ppc64:
1584   case llvm::Triple::ppc64le:
1585     AddPPCTargetArgs(Args, CmdArgs);
1586     break;
1587 
1588   case llvm::Triple::riscv32:
1589   case llvm::Triple::riscv64:
1590     AddRISCVTargetArgs(Args, CmdArgs);
1591     break;
1592 
1593   case llvm::Triple::sparc:
1594   case llvm::Triple::sparcel:
1595   case llvm::Triple::sparcv9:
1596     AddSparcTargetArgs(Args, CmdArgs);
1597     break;
1598 
1599   case llvm::Triple::systemz:
1600     AddSystemZTargetArgs(Args, CmdArgs);
1601     break;
1602 
1603   case llvm::Triple::x86:
1604   case llvm::Triple::x86_64:
1605     AddX86TargetArgs(Args, CmdArgs);
1606     break;
1607 
1608   case llvm::Triple::lanai:
1609     AddLanaiTargetArgs(Args, CmdArgs);
1610     break;
1611 
1612   case llvm::Triple::hexagon:
1613     AddHexagonTargetArgs(Args, CmdArgs);
1614     break;
1615 
1616   case llvm::Triple::wasm32:
1617   case llvm::Triple::wasm64:
1618     AddWebAssemblyTargetArgs(Args, CmdArgs);
1619     break;
1620 
1621   case llvm::Triple::ve:
1622     AddVETargetArgs(Args, CmdArgs);
1623     break;
1624   }
1625 }
1626 
1627 namespace {
RenderAArch64ABI(const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs)1628 void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1629                       ArgStringList &CmdArgs) {
1630   const char *ABIName = nullptr;
1631   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1632     ABIName = A->getValue();
1633   else if (Triple.isOSDarwin())
1634     ABIName = "darwinpcs";
1635   else if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1636     ABIName = "pauthtest";
1637   else
1638     ABIName = "aapcs";
1639 
1640   CmdArgs.push_back("-target-abi");
1641   CmdArgs.push_back(ABIName);
1642 }
1643 }
1644 
AddAArch64TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1645 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1646                                  ArgStringList &CmdArgs) const {
1647   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1648 
1649   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1650       Args.hasArg(options::OPT_mkernel) ||
1651       Args.hasArg(options::OPT_fapple_kext))
1652     CmdArgs.push_back("-disable-red-zone");
1653 
1654   if (!Args.hasFlag(options::OPT_mimplicit_float,
1655                     options::OPT_mno_implicit_float, true))
1656     CmdArgs.push_back("-no-implicit-float");
1657 
1658   RenderAArch64ABI(Triple, Args, CmdArgs);
1659 
1660   // Forward the -mglobal-merge option for explicit control over the pass.
1661   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1662                                options::OPT_mno_global_merge)) {
1663     CmdArgs.push_back("-mllvm");
1664     if (A->getOption().matches(options::OPT_mno_global_merge))
1665       CmdArgs.push_back("-aarch64-enable-global-merge=false");
1666     else
1667       CmdArgs.push_back("-aarch64-enable-global-merge=true");
1668   }
1669 
1670   // Handle -msve_vector_bits=<bits>
1671   auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1672                               StringRef VScaleMax) {
1673     StringRef Val = A->getValue();
1674     const Driver &D = getToolChain().getDriver();
1675     if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1676         Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1677         Val == "1024+" || Val == "2048+") {
1678       unsigned Bits = 0;
1679       if (!Val.consume_back("+")) {
1680         bool Invalid = Val.getAsInteger(10, Bits);
1681         (void)Invalid;
1682         assert(!Invalid && "Failed to parse value");
1683         CmdArgs.push_back(
1684             Args.MakeArgString(VScaleMax + llvm::Twine(Bits / 128)));
1685       }
1686 
1687       bool Invalid = Val.getAsInteger(10, Bits);
1688       (void)Invalid;
1689       assert(!Invalid && "Failed to parse value");
1690 
1691       CmdArgs.push_back(
1692           Args.MakeArgString(VScaleMin + llvm::Twine(Bits / 128)));
1693     } else if (Val == "scalable") {
1694       // Silently drop requests for vector-length agnostic code as it's implied.
1695     } else {
1696       // Handle the unsupported values passed to msve-vector-bits.
1697       D.Diag(diag::err_drv_unsupported_option_argument)
1698           << A->getSpelling() << Val;
1699     }
1700   };
1701   if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))
1702     HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1703   if (Arg *A = Args.getLastArg(options::OPT_msve_streaming_vector_bits_EQ))
1704     HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1705 
1706   AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1707 
1708   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1709     CmdArgs.push_back("-tune-cpu");
1710     if (strcmp(A->getValue(), "native") == 0)
1711       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
1712     else
1713       CmdArgs.push_back(A->getValue());
1714   }
1715 
1716   AddUnalignedAccessWarning(CmdArgs);
1717 
1718   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1719                     options::OPT_fno_ptrauth_intrinsics);
1720   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1721                     options::OPT_fno_ptrauth_calls);
1722   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1723                     options::OPT_fno_ptrauth_returns);
1724   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1725                     options::OPT_fno_ptrauth_auth_traps);
1726   Args.addOptInFlag(
1727       CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1728       options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1729   Args.addOptInFlag(
1730       CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1731       options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1732   Args.addOptInFlag(
1733       CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1734       options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1735   Args.addOptInFlag(
1736       CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
1737       options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1738 
1739   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
1740                     options::OPT_fno_ptrauth_indirect_gotos);
1741   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1742                     options::OPT_fno_ptrauth_init_fini);
1743   Args.addOptInFlag(CmdArgs,
1744                     options::OPT_fptrauth_init_fini_address_discrimination,
1745                     options::OPT_fno_ptrauth_init_fini_address_discrimination);
1746   Args.addOptInFlag(CmdArgs, options::OPT_faarch64_jump_table_hardening,
1747                     options::OPT_fno_aarch64_jump_table_hardening);
1748 
1749   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_isa,
1750                     options::OPT_fno_ptrauth_objc_isa);
1751   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_interface_sel,
1752                     options::OPT_fno_ptrauth_objc_interface_sel);
1753   Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_class_ro,
1754                     options::OPT_fno_ptrauth_objc_class_ro);
1755   if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1756     handlePAuthABI(Args, CmdArgs);
1757 
1758   // Enable/disable return address signing and indirect branch targets.
1759   CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1760 }
1761 
AddLoongArchTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1762 void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1763                                    ArgStringList &CmdArgs) const {
1764   const llvm::Triple &Triple = getToolChain().getTriple();
1765 
1766   CmdArgs.push_back("-target-abi");
1767   CmdArgs.push_back(
1768       loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1769           .data());
1770 
1771   // Handle -mtune.
1772   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1773     std::string TuneCPU = A->getValue();
1774     TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1775     CmdArgs.push_back("-tune-cpu");
1776     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1777   }
1778 
1779   if (Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
1780                                options::OPT_mno_annotate_tablejump)) {
1781     if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
1782       CmdArgs.push_back("-mllvm");
1783       CmdArgs.push_back("-loongarch-annotate-tablejump");
1784     }
1785   }
1786 }
1787 
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1788 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1789                               ArgStringList &CmdArgs) const {
1790   const Driver &D = getToolChain().getDriver();
1791   StringRef CPUName;
1792   StringRef ABIName;
1793   const llvm::Triple &Triple = getToolChain().getTriple();
1794   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1795 
1796   CmdArgs.push_back("-target-abi");
1797   CmdArgs.push_back(ABIName.data());
1798 
1799   mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1800   if (ABI == mips::FloatABI::Soft) {
1801     // Floating point operations and argument passing are soft.
1802     CmdArgs.push_back("-msoft-float");
1803     CmdArgs.push_back("-mfloat-abi");
1804     CmdArgs.push_back("soft");
1805   } else {
1806     // Floating point operations and argument passing are hard.
1807     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1808     CmdArgs.push_back("-mfloat-abi");
1809     CmdArgs.push_back("hard");
1810   }
1811 
1812   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1813                                options::OPT_mno_ldc1_sdc1)) {
1814     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1815       CmdArgs.push_back("-mllvm");
1816       CmdArgs.push_back("-mno-ldc1-sdc1");
1817     }
1818   }
1819 
1820   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1821                                options::OPT_mno_check_zero_division)) {
1822     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1823       CmdArgs.push_back("-mllvm");
1824       CmdArgs.push_back("-mno-check-zero-division");
1825     }
1826   }
1827 
1828   if (Args.getLastArg(options::OPT_mfix4300)) {
1829     CmdArgs.push_back("-mllvm");
1830     CmdArgs.push_back("-mfix4300");
1831   }
1832 
1833   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1834     StringRef v = A->getValue();
1835     CmdArgs.push_back("-mllvm");
1836     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1837     A->claim();
1838   }
1839 
1840   Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1841   Arg *ABICalls =
1842       Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1843 
1844   // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1845   // -mgpopt is the default for static, -fno-pic environments but these two
1846   // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1847   // the only case where -mllvm -mgpopt is passed.
1848   // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1849   //       passed explicitly when compiling something with -mabicalls
1850   //       (implictly) in affect. Currently the warning is in the backend.
1851   //
1852   // When the ABI in use is  N64, we also need to determine the PIC mode that
1853   // is in use, as -fno-pic for N64 implies -mno-abicalls.
1854   bool NoABICalls =
1855       ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1856 
1857   llvm::Reloc::Model RelocationModel;
1858   unsigned PICLevel;
1859   bool IsPIE;
1860   std::tie(RelocationModel, PICLevel, IsPIE) =
1861       ParsePICArgs(getToolChain(), Args);
1862 
1863   NoABICalls = NoABICalls ||
1864                (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1865 
1866   bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1867   // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1868   if (NoABICalls && (!GPOpt || WantGPOpt)) {
1869     CmdArgs.push_back("-mllvm");
1870     CmdArgs.push_back("-mgpopt");
1871 
1872     Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1873                                       options::OPT_mno_local_sdata);
1874     Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1875                                        options::OPT_mno_extern_sdata);
1876     Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1877                                         options::OPT_mno_embedded_data);
1878     if (LocalSData) {
1879       CmdArgs.push_back("-mllvm");
1880       if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1881         CmdArgs.push_back("-mlocal-sdata=1");
1882       } else {
1883         CmdArgs.push_back("-mlocal-sdata=0");
1884       }
1885       LocalSData->claim();
1886     }
1887 
1888     if (ExternSData) {
1889       CmdArgs.push_back("-mllvm");
1890       if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1891         CmdArgs.push_back("-mextern-sdata=1");
1892       } else {
1893         CmdArgs.push_back("-mextern-sdata=0");
1894       }
1895       ExternSData->claim();
1896     }
1897 
1898     if (EmbeddedData) {
1899       CmdArgs.push_back("-mllvm");
1900       if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1901         CmdArgs.push_back("-membedded-data=1");
1902       } else {
1903         CmdArgs.push_back("-membedded-data=0");
1904       }
1905       EmbeddedData->claim();
1906     }
1907 
1908   } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1909     D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1910 
1911   if (GPOpt)
1912     GPOpt->claim();
1913 
1914   if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1915     StringRef Val = StringRef(A->getValue());
1916     if (mips::hasCompactBranches(CPUName)) {
1917       if (Val == "never" || Val == "always" || Val == "optimal") {
1918         CmdArgs.push_back("-mllvm");
1919         CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1920       } else
1921         D.Diag(diag::err_drv_unsupported_option_argument)
1922             << A->getSpelling() << Val;
1923     } else
1924       D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1925   }
1926 
1927   if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1928                                options::OPT_mno_relax_pic_calls)) {
1929     if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1930       CmdArgs.push_back("-mllvm");
1931       CmdArgs.push_back("-mips-jalr-reloc=0");
1932     }
1933   }
1934 }
1935 
AddPPCTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1936 void Clang::AddPPCTargetArgs(const ArgList &Args,
1937                              ArgStringList &CmdArgs) const {
1938   const Driver &D = getToolChain().getDriver();
1939   const llvm::Triple &T = getToolChain().getTriple();
1940   if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1941     CmdArgs.push_back("-tune-cpu");
1942     StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, A->getValue());
1943     CmdArgs.push_back(Args.MakeArgString(CPU.str()));
1944   }
1945 
1946   // Select the ABI to use.
1947   const char *ABIName = nullptr;
1948   if (T.isOSBinFormatELF()) {
1949     switch (getToolChain().getArch()) {
1950     case llvm::Triple::ppc64: {
1951       if (T.isPPC64ELFv2ABI())
1952         ABIName = "elfv2";
1953       else
1954         ABIName = "elfv1";
1955       break;
1956     }
1957     case llvm::Triple::ppc64le:
1958       ABIName = "elfv2";
1959       break;
1960     default:
1961       break;
1962     }
1963   }
1964 
1965   bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1966   bool VecExtabi = false;
1967   for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1968     StringRef V = A->getValue();
1969     if (V == "ieeelongdouble") {
1970       IEEELongDouble = true;
1971       A->claim();
1972     } else if (V == "ibmlongdouble") {
1973       IEEELongDouble = false;
1974       A->claim();
1975     } else if (V == "vec-default") {
1976       VecExtabi = false;
1977       A->claim();
1978     } else if (V == "vec-extabi") {
1979       VecExtabi = true;
1980       A->claim();
1981     } else if (V == "elfv1") {
1982       ABIName = "elfv1";
1983       A->claim();
1984     } else if (V == "elfv2") {
1985       ABIName = "elfv2";
1986       A->claim();
1987     } else if (V != "altivec")
1988       // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1989       // the option if given as we don't have backend support for any targets
1990       // that don't use the altivec abi.
1991       ABIName = A->getValue();
1992   }
1993   if (IEEELongDouble)
1994     CmdArgs.push_back("-mabi=ieeelongdouble");
1995   if (VecExtabi) {
1996     if (!T.isOSAIX())
1997       D.Diag(diag::err_drv_unsupported_opt_for_target)
1998           << "-mabi=vec-extabi" << T.str();
1999     CmdArgs.push_back("-mabi=vec-extabi");
2000   }
2001 
2002   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true))
2003     CmdArgs.push_back("-disable-red-zone");
2004 
2005   ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
2006   if (FloatABI == ppc::FloatABI::Soft) {
2007     // Floating point operations and argument passing are soft.
2008     CmdArgs.push_back("-msoft-float");
2009     CmdArgs.push_back("-mfloat-abi");
2010     CmdArgs.push_back("soft");
2011   } else {
2012     // Floating point operations and argument passing are hard.
2013     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2014     CmdArgs.push_back("-mfloat-abi");
2015     CmdArgs.push_back("hard");
2016   }
2017 
2018   if (ABIName) {
2019     CmdArgs.push_back("-target-abi");
2020     CmdArgs.push_back(ABIName);
2021   }
2022 }
2023 
AddRISCVTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2024 void Clang::AddRISCVTargetArgs(const ArgList &Args,
2025                                ArgStringList &CmdArgs) const {
2026   const llvm::Triple &Triple = getToolChain().getTriple();
2027   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2028 
2029   CmdArgs.push_back("-target-abi");
2030   CmdArgs.push_back(ABIName.data());
2031 
2032   if (Arg *A = Args.getLastArg(options::OPT_G)) {
2033     CmdArgs.push_back("-msmall-data-limit");
2034     CmdArgs.push_back(A->getValue());
2035   }
2036 
2037   if (!Args.hasFlag(options::OPT_mimplicit_float,
2038                     options::OPT_mno_implicit_float, true))
2039     CmdArgs.push_back("-no-implicit-float");
2040 
2041   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2042     CmdArgs.push_back("-tune-cpu");
2043     if (strcmp(A->getValue(), "native") == 0)
2044       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2045     else
2046       CmdArgs.push_back(A->getValue());
2047   }
2048 
2049   // Handle -mrvv-vector-bits=<bits>
2050   if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2051     StringRef Val = A->getValue();
2052     const Driver &D = getToolChain().getDriver();
2053 
2054     // Get minimum VLen from march.
2055     unsigned MinVLen = 0;
2056     std::string Arch = riscv::getRISCVArch(Args, Triple);
2057     auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2058         Arch, /*EnableExperimentalExtensions*/ true);
2059     // Ignore parsing error.
2060     if (!errorToBool(ISAInfo.takeError()))
2061       MinVLen = (*ISAInfo)->getMinVLen();
2062 
2063     // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2064     // as integer as long as we have a MinVLen.
2065     unsigned Bits = 0;
2066     if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2067       Bits = MinVLen;
2068     } else if (!Val.getAsInteger(10, Bits)) {
2069       // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2070       // at least MinVLen.
2071       if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2072           Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2073         Bits = 0;
2074     }
2075 
2076     // If we got a valid value try to use it.
2077     if (Bits != 0) {
2078       unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2079       CmdArgs.push_back(
2080           Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2081       CmdArgs.push_back(
2082           Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2083     } else if (Val != "scalable") {
2084       // Handle the unsupported values passed to mrvv-vector-bits.
2085       D.Diag(diag::err_drv_unsupported_option_argument)
2086           << A->getSpelling() << Val;
2087     }
2088   }
2089 }
2090 
AddSparcTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2091 void Clang::AddSparcTargetArgs(const ArgList &Args,
2092                                ArgStringList &CmdArgs) const {
2093   sparc::FloatABI FloatABI =
2094       sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2095 
2096   if (FloatABI == sparc::FloatABI::Soft) {
2097     // Floating point operations and argument passing are soft.
2098     CmdArgs.push_back("-msoft-float");
2099     CmdArgs.push_back("-mfloat-abi");
2100     CmdArgs.push_back("soft");
2101   } else {
2102     // Floating point operations and argument passing are hard.
2103     assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2104     CmdArgs.push_back("-mfloat-abi");
2105     CmdArgs.push_back("hard");
2106   }
2107 
2108   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2109     StringRef Name = A->getValue();
2110     std::string TuneCPU;
2111     if (Name == "native")
2112       TuneCPU = std::string(llvm::sys::getHostCPUName());
2113     else
2114       TuneCPU = std::string(Name);
2115 
2116     CmdArgs.push_back("-tune-cpu");
2117     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2118   }
2119 }
2120 
AddSystemZTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2121 void Clang::AddSystemZTargetArgs(const ArgList &Args,
2122                                  ArgStringList &CmdArgs) const {
2123   if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2124     CmdArgs.push_back("-tune-cpu");
2125     if (strcmp(A->getValue(), "native") == 0)
2126       CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2127     else
2128       CmdArgs.push_back(A->getValue());
2129   }
2130 
2131   bool HasBackchain =
2132       Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2133   bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2134                                      options::OPT_mno_packed_stack, false);
2135   systemz::FloatABI FloatABI =
2136       systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2137   bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2138   if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2139     const Driver &D = getToolChain().getDriver();
2140     D.Diag(diag::err_drv_unsupported_opt)
2141       << "-mpacked-stack -mbackchain -mhard-float";
2142   }
2143   if (HasBackchain)
2144     CmdArgs.push_back("-mbackchain");
2145   if (HasPackedStack)
2146     CmdArgs.push_back("-mpacked-stack");
2147   if (HasSoftFloat) {
2148     // Floating point operations and argument passing are soft.
2149     CmdArgs.push_back("-msoft-float");
2150     CmdArgs.push_back("-mfloat-abi");
2151     CmdArgs.push_back("soft");
2152   }
2153 }
2154 
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2155 void Clang::AddX86TargetArgs(const ArgList &Args,
2156                              ArgStringList &CmdArgs) const {
2157   const Driver &D = getToolChain().getDriver();
2158   addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2159 
2160   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2161       Args.hasArg(options::OPT_mkernel) ||
2162       Args.hasArg(options::OPT_fapple_kext))
2163     CmdArgs.push_back("-disable-red-zone");
2164 
2165   if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2166                     options::OPT_mno_tls_direct_seg_refs, true))
2167     CmdArgs.push_back("-mno-tls-direct-seg-refs");
2168 
2169   // Default to avoid implicit floating-point for kernel/kext code, but allow
2170   // that to be overridden with -mno-soft-float.
2171   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2172                           Args.hasArg(options::OPT_fapple_kext));
2173   if (Arg *A = Args.getLastArg(
2174           options::OPT_msoft_float, options::OPT_mno_soft_float,
2175           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2176     const Option &O = A->getOption();
2177     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2178                        O.matches(options::OPT_msoft_float));
2179   }
2180   if (NoImplicitFloat)
2181     CmdArgs.push_back("-no-implicit-float");
2182 
2183   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2184     StringRef Value = A->getValue();
2185     if (Value == "intel" || Value == "att") {
2186       CmdArgs.push_back("-mllvm");
2187       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2188       CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2189     } else {
2190       D.Diag(diag::err_drv_unsupported_option_argument)
2191           << A->getSpelling() << Value;
2192     }
2193   } else if (D.IsCLMode()) {
2194     CmdArgs.push_back("-mllvm");
2195     CmdArgs.push_back("-x86-asm-syntax=intel");
2196   }
2197 
2198   if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2199                                options::OPT_mno_skip_rax_setup))
2200     if (A->getOption().matches(options::OPT_mskip_rax_setup))
2201       CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2202 
2203   // Set flags to support MCU ABI.
2204   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2205     CmdArgs.push_back("-mfloat-abi");
2206     CmdArgs.push_back("soft");
2207     CmdArgs.push_back("-mstack-alignment=4");
2208   }
2209 
2210   // Handle -mtune.
2211 
2212   // Default to "generic" unless -march is present or targetting the PS4/PS5.
2213   std::string TuneCPU;
2214   if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2215       !getToolChain().getTriple().isPS())
2216     TuneCPU = "generic";
2217 
2218   // Override based on -mtune.
2219   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2220     StringRef Name = A->getValue();
2221 
2222     if (Name == "native") {
2223       Name = llvm::sys::getHostCPUName();
2224       if (!Name.empty())
2225         TuneCPU = std::string(Name);
2226     } else
2227       TuneCPU = std::string(Name);
2228   }
2229 
2230   if (!TuneCPU.empty()) {
2231     CmdArgs.push_back("-tune-cpu");
2232     CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2233   }
2234 }
2235 
AddHexagonTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2236 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2237                                  ArgStringList &CmdArgs) const {
2238   CmdArgs.push_back("-mqdsp6-compat");
2239   CmdArgs.push_back("-Wreturn-type");
2240 
2241   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2242     CmdArgs.push_back("-mllvm");
2243     CmdArgs.push_back(
2244         Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2245   }
2246 
2247   if (!Args.hasArg(options::OPT_fno_short_enums))
2248     CmdArgs.push_back("-fshort-enums");
2249   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2250     CmdArgs.push_back("-mllvm");
2251     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2252   }
2253   CmdArgs.push_back("-mllvm");
2254   CmdArgs.push_back("-machine-sink-split=0");
2255 }
2256 
AddLanaiTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2257 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2258                                ArgStringList &CmdArgs) const {
2259   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2260     StringRef CPUName = A->getValue();
2261 
2262     CmdArgs.push_back("-target-cpu");
2263     CmdArgs.push_back(Args.MakeArgString(CPUName));
2264   }
2265   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2266     StringRef Value = A->getValue();
2267     // Only support mregparm=4 to support old usage. Report error for all other
2268     // cases.
2269     int Mregparm;
2270     if (Value.getAsInteger(10, Mregparm)) {
2271       if (Mregparm != 4) {
2272         getToolChain().getDriver().Diag(
2273             diag::err_drv_unsupported_option_argument)
2274             << A->getSpelling() << Value;
2275       }
2276     }
2277   }
2278 }
2279 
AddWebAssemblyTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2280 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2281                                      ArgStringList &CmdArgs) const {
2282   // Default to "hidden" visibility.
2283   if (!Args.hasArg(options::OPT_fvisibility_EQ,
2284                    options::OPT_fvisibility_ms_compat))
2285     CmdArgs.push_back("-fvisibility=hidden");
2286 }
2287 
AddVETargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2288 void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2289   // Floating point operations and argument passing are hard.
2290   CmdArgs.push_back("-mfloat-abi");
2291   CmdArgs.push_back("hard");
2292 }
2293 
DumpCompilationDatabase(Compilation & C,StringRef Filename,StringRef Target,const InputInfo & Output,const InputInfo & Input,const ArgList & Args) const2294 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2295                                     StringRef Target, const InputInfo &Output,
2296                                     const InputInfo &Input, const ArgList &Args) const {
2297   // If this is a dry run, do not create the compilation database file.
2298   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2299     return;
2300 
2301   using llvm::yaml::escape;
2302   const Driver &D = getToolChain().getDriver();
2303 
2304   if (!CompilationDatabase) {
2305     std::error_code EC;
2306     auto File = std::make_unique<llvm::raw_fd_ostream>(
2307         Filename, EC,
2308         llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2309     if (EC) {
2310       D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2311                                                        << EC.message();
2312       return;
2313     }
2314     CompilationDatabase = std::move(File);
2315   }
2316   auto &CDB = *CompilationDatabase;
2317   auto CWD = D.getVFS().getCurrentWorkingDirectory();
2318   if (!CWD)
2319     CWD = ".";
2320   CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2321   CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2322   if (Output.isFilename())
2323     CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2324   CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2325   SmallString<128> Buf;
2326   Buf = "-x";
2327   Buf += types::getTypeName(Input.getType());
2328   CDB << ", \"" << escape(Buf) << "\"";
2329   if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2330     Buf = "--sysroot=";
2331     Buf += D.SysRoot;
2332     CDB << ", \"" << escape(Buf) << "\"";
2333   }
2334   CDB << ", \"" << escape(Input.getFilename()) << "\"";
2335   if (Output.isFilename())
2336     CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2337   for (auto &A: Args) {
2338     auto &O = A->getOption();
2339     // Skip language selection, which is positional.
2340     if (O.getID() == options::OPT_x)
2341       continue;
2342     // Skip writing dependency output and the compilation database itself.
2343     if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2344       continue;
2345     if (O.getID() == options::OPT_gen_cdb_fragment_path)
2346       continue;
2347     // Skip inputs.
2348     if (O.getKind() == Option::InputClass)
2349       continue;
2350     // Skip output.
2351     if (O.getID() == options::OPT_o)
2352       continue;
2353     // All other arguments are quoted and appended.
2354     ArgStringList ASL;
2355     A->render(Args, ASL);
2356     for (auto &it: ASL)
2357       CDB << ", \"" << escape(it) << "\"";
2358   }
2359   Buf = "--target=";
2360   Buf += Target;
2361   CDB << ", \"" << escape(Buf) << "\"]},\n";
2362 }
2363 
DumpCompilationDatabaseFragmentToDir(StringRef Dir,Compilation & C,StringRef Target,const InputInfo & Output,const InputInfo & Input,const llvm::opt::ArgList & Args) const2364 void Clang::DumpCompilationDatabaseFragmentToDir(
2365     StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2366     const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2367   // If this is a dry run, do not create the compilation database file.
2368   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2369     return;
2370 
2371   if (CompilationDatabase)
2372     DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2373 
2374   SmallString<256> Path = Dir;
2375   const auto &Driver = C.getDriver();
2376   Driver.getVFS().makeAbsolute(Path);
2377   auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2378   if (Err) {
2379     Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2380     return;
2381   }
2382 
2383   llvm::sys::path::append(
2384       Path,
2385       Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2386   int FD;
2387   SmallString<256> TempPath;
2388   Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2389                                         llvm::sys::fs::OF_Text);
2390   if (Err) {
2391     Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2392     return;
2393   }
2394   CompilationDatabase =
2395       std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2396   DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2397 }
2398 
CheckARMImplicitITArg(StringRef Value)2399 static bool CheckARMImplicitITArg(StringRef Value) {
2400   return Value == "always" || Value == "never" || Value == "arm" ||
2401          Value == "thumb";
2402 }
2403 
AddARMImplicitITArgs(const ArgList & Args,ArgStringList & CmdArgs,StringRef Value)2404 static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2405                                  StringRef Value) {
2406   CmdArgs.push_back("-mllvm");
2407   CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2408 }
2409 
CollectArgsForIntegratedAssembler(Compilation & C,const ArgList & Args,ArgStringList & CmdArgs,const Driver & D)2410 static void CollectArgsForIntegratedAssembler(Compilation &C,
2411                                               const ArgList &Args,
2412                                               ArgStringList &CmdArgs,
2413                                               const Driver &D) {
2414   // Default to -mno-relax-all.
2415   //
2416   // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2417   // cannot be done by assembler branch relaxation as it needs a free temporary
2418   // register. Because of this, branch relaxation is handled by a MachineIR pass
2419   // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2420   // MachineIR branch relaxation inaccurate and it will miss cases where an
2421   // indirect branch is necessary.
2422   Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2423                     options::OPT_mno_relax_all);
2424 
2425   // Only default to -mincremental-linker-compatible if we think we are
2426   // targeting the MSVC linker.
2427   bool DefaultIncrementalLinkerCompatible =
2428       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2429   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2430                    options::OPT_mno_incremental_linker_compatible,
2431                    DefaultIncrementalLinkerCompatible))
2432     CmdArgs.push_back("-mincremental-linker-compatible");
2433 
2434   Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2435 
2436   Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2437                     options::OPT_fno_emit_compact_unwind_non_canonical);
2438 
2439   // If you add more args here, also add them to the block below that
2440   // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2441 
2442   // When passing -I arguments to the assembler we sometimes need to
2443   // unconditionally take the next argument.  For example, when parsing
2444   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2445   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2446   // arg after parsing the '-I' arg.
2447   bool TakeNextArg = false;
2448 
2449   const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2450   bool IsELF = Triple.isOSBinFormatELF();
2451   bool Crel = false, ExperimentalCrel = false;
2452   bool ImplicitMapSyms = false;
2453   bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2454   bool UseNoExecStack = false;
2455   bool Msa = false;
2456   const char *MipsTargetFeature = nullptr;
2457   llvm::SmallVector<const char *> SparcTargetFeatures;
2458   StringRef ImplicitIt;
2459   for (const Arg *A :
2460        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2461                      options::OPT_mimplicit_it_EQ)) {
2462     A->claim();
2463 
2464     if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2465       switch (C.getDefaultToolChain().getArch()) {
2466       case llvm::Triple::arm:
2467       case llvm::Triple::armeb:
2468       case llvm::Triple::thumb:
2469       case llvm::Triple::thumbeb:
2470         // Only store the value; the last value set takes effect.
2471         ImplicitIt = A->getValue();
2472         if (!CheckARMImplicitITArg(ImplicitIt))
2473           D.Diag(diag::err_drv_unsupported_option_argument)
2474               << A->getSpelling() << ImplicitIt;
2475         continue;
2476       default:
2477         break;
2478       }
2479     }
2480 
2481     for (StringRef Value : A->getValues()) {
2482       if (TakeNextArg) {
2483         CmdArgs.push_back(Value.data());
2484         TakeNextArg = false;
2485         continue;
2486       }
2487 
2488       if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2489           Value == "-mbig-obj")
2490         continue; // LLVM handles bigobj automatically
2491 
2492       auto Equal = Value.split('=');
2493       auto checkArg = [&](bool ValidTarget,
2494                           std::initializer_list<const char *> Set) {
2495         if (!ValidTarget) {
2496           D.Diag(diag::err_drv_unsupported_opt_for_target)
2497               << (Twine("-Wa,") + Equal.first + "=").str()
2498               << Triple.getTriple();
2499         } else if (!llvm::is_contained(Set, Equal.second)) {
2500           D.Diag(diag::err_drv_unsupported_option_argument)
2501               << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2502         }
2503       };
2504       switch (C.getDefaultToolChain().getArch()) {
2505       default:
2506         break;
2507       case llvm::Triple::x86:
2508       case llvm::Triple::x86_64:
2509         if (Equal.first == "-mrelax-relocations" ||
2510             Equal.first == "--mrelax-relocations") {
2511           UseRelaxRelocations = Equal.second == "yes";
2512           checkArg(IsELF, {"yes", "no"});
2513           continue;
2514         }
2515         if (Value == "-msse2avx") {
2516           CmdArgs.push_back("-msse2avx");
2517           continue;
2518         }
2519         break;
2520       case llvm::Triple::wasm32:
2521       case llvm::Triple::wasm64:
2522         if (Value == "--no-type-check") {
2523           CmdArgs.push_back("-mno-type-check");
2524           continue;
2525         }
2526         break;
2527       case llvm::Triple::thumb:
2528       case llvm::Triple::thumbeb:
2529       case llvm::Triple::arm:
2530       case llvm::Triple::armeb:
2531         if (Equal.first == "-mimplicit-it") {
2532           // Only store the value; the last value set takes effect.
2533           ImplicitIt = Equal.second;
2534           checkArg(true, {"always", "never", "arm", "thumb"});
2535           continue;
2536         }
2537         if (Value == "-mthumb")
2538           // -mthumb has already been processed in ComputeLLVMTriple()
2539           // recognize but skip over here.
2540           continue;
2541         break;
2542       case llvm::Triple::aarch64:
2543       case llvm::Triple::aarch64_be:
2544       case llvm::Triple::aarch64_32:
2545         if (Equal.first == "-mmapsyms") {
2546           ImplicitMapSyms = Equal.second == "implicit";
2547           checkArg(IsELF, {"default", "implicit"});
2548           continue;
2549         }
2550         break;
2551       case llvm::Triple::mips:
2552       case llvm::Triple::mipsel:
2553       case llvm::Triple::mips64:
2554       case llvm::Triple::mips64el:
2555         if (Value == "--trap") {
2556           CmdArgs.push_back("-target-feature");
2557           CmdArgs.push_back("+use-tcc-in-div");
2558           continue;
2559         }
2560         if (Value == "--break") {
2561           CmdArgs.push_back("-target-feature");
2562           CmdArgs.push_back("-use-tcc-in-div");
2563           continue;
2564         }
2565         if (Value.starts_with("-msoft-float")) {
2566           CmdArgs.push_back("-target-feature");
2567           CmdArgs.push_back("+soft-float");
2568           continue;
2569         }
2570         if (Value.starts_with("-mhard-float")) {
2571           CmdArgs.push_back("-target-feature");
2572           CmdArgs.push_back("-soft-float");
2573           continue;
2574         }
2575         if (Value == "-mmsa") {
2576           Msa = true;
2577           continue;
2578         }
2579         if (Value == "-mno-msa") {
2580           Msa = false;
2581           continue;
2582         }
2583         MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2584                                 .Case("-mips1", "+mips1")
2585                                 .Case("-mips2", "+mips2")
2586                                 .Case("-mips3", "+mips3")
2587                                 .Case("-mips4", "+mips4")
2588                                 .Case("-mips5", "+mips5")
2589                                 .Case("-mips32", "+mips32")
2590                                 .Case("-mips32r2", "+mips32r2")
2591                                 .Case("-mips32r3", "+mips32r3")
2592                                 .Case("-mips32r5", "+mips32r5")
2593                                 .Case("-mips32r6", "+mips32r6")
2594                                 .Case("-mips64", "+mips64")
2595                                 .Case("-mips64r2", "+mips64r2")
2596                                 .Case("-mips64r3", "+mips64r3")
2597                                 .Case("-mips64r5", "+mips64r5")
2598                                 .Case("-mips64r6", "+mips64r6")
2599                                 .Default(nullptr);
2600         if (MipsTargetFeature)
2601           continue;
2602         break;
2603 
2604       case llvm::Triple::sparc:
2605       case llvm::Triple::sparcel:
2606       case llvm::Triple::sparcv9:
2607         if (Value == "--undeclared-regs") {
2608           // LLVM already allows undeclared use of G registers, so this option
2609           // becomes a no-op. This solely exists for GNU compatibility.
2610           // TODO implement --no-undeclared-regs
2611           continue;
2612         }
2613         SparcTargetFeatures =
2614             llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2615                 .Case("-Av8", {"-v8plus"})
2616                 .Case("-Av8plus", {"+v8plus", "+v9"})
2617                 .Case("-Av8plusa", {"+v8plus", "+v9", "+vis"})
2618                 .Case("-Av8plusb", {"+v8plus", "+v9", "+vis", "+vis2"})
2619                 .Case("-Av8plusd", {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2620                 .Case("-Av9", {"+v9"})
2621                 .Case("-Av9a", {"+v9", "+vis"})
2622                 .Case("-Av9b", {"+v9", "+vis", "+vis2"})
2623                 .Case("-Av9d", {"+v9", "+vis", "+vis2", "+vis3"})
2624                 .Default({});
2625         if (!SparcTargetFeatures.empty())
2626           continue;
2627         break;
2628       }
2629 
2630       if (Value == "-force_cpusubtype_ALL") {
2631         // Do nothing, this is the default and we don't support anything else.
2632       } else if (Value == "-L") {
2633         CmdArgs.push_back("-msave-temp-labels");
2634       } else if (Value == "--fatal-warnings") {
2635         CmdArgs.push_back("-massembler-fatal-warnings");
2636       } else if (Value == "--no-warn" || Value == "-W") {
2637         CmdArgs.push_back("-massembler-no-warn");
2638       } else if (Value == "--noexecstack") {
2639         UseNoExecStack = true;
2640       } else if (Value.starts_with("-compress-debug-sections") ||
2641                  Value.starts_with("--compress-debug-sections") ||
2642                  Value == "-nocompress-debug-sections" ||
2643                  Value == "--nocompress-debug-sections") {
2644         CmdArgs.push_back(Value.data());
2645       } else if (Value == "--crel") {
2646         Crel = true;
2647       } else if (Value == "--no-crel") {
2648         Crel = false;
2649       } else if (Value == "--allow-experimental-crel") {
2650         ExperimentalCrel = true;
2651       } else if (Value.starts_with("-I")) {
2652         CmdArgs.push_back(Value.data());
2653         // We need to consume the next argument if the current arg is a plain
2654         // -I. The next arg will be the include directory.
2655         if (Value == "-I")
2656           TakeNextArg = true;
2657       } else if (Value.starts_with("-gdwarf-")) {
2658         // "-gdwarf-N" options are not cc1as options.
2659         unsigned DwarfVersion = DwarfVersionNum(Value);
2660         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2661           CmdArgs.push_back(Value.data());
2662         } else {
2663           RenderDebugEnablingArgs(Args, CmdArgs,
2664                                   llvm::codegenoptions::DebugInfoConstructor,
2665                                   DwarfVersion, llvm::DebuggerKind::Default);
2666         }
2667       } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2668                  Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2669         // Do nothing, we'll validate it later.
2670       } else if (Value == "-defsym" || Value == "--defsym") {
2671         if (A->getNumValues() != 2) {
2672           D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2673           break;
2674         }
2675         const char *S = A->getValue(1);
2676         auto Pair = StringRef(S).split('=');
2677         auto Sym = Pair.first;
2678         auto SVal = Pair.second;
2679 
2680         if (Sym.empty() || SVal.empty()) {
2681           D.Diag(diag::err_drv_defsym_invalid_format) << S;
2682           break;
2683         }
2684         int64_t IVal;
2685         if (SVal.getAsInteger(0, IVal)) {
2686           D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2687           break;
2688         }
2689         CmdArgs.push_back("--defsym");
2690         TakeNextArg = true;
2691       } else if (Value == "-fdebug-compilation-dir") {
2692         CmdArgs.push_back("-fdebug-compilation-dir");
2693         TakeNextArg = true;
2694       } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2695         // The flag is a -Wa / -Xassembler argument and Options doesn't
2696         // parse the argument, so this isn't automatically aliased to
2697         // -fdebug-compilation-dir (without '=') here.
2698         CmdArgs.push_back("-fdebug-compilation-dir");
2699         CmdArgs.push_back(Value.data());
2700       } else if (Value == "--version") {
2701         D.PrintVersion(C, llvm::outs());
2702       } else {
2703         D.Diag(diag::err_drv_unsupported_option_argument)
2704             << A->getSpelling() << Value;
2705       }
2706     }
2707   }
2708   if (ImplicitIt.size())
2709     AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2710   if (Crel) {
2711     if (!ExperimentalCrel)
2712       D.Diag(diag::err_drv_experimental_crel);
2713     if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2714       CmdArgs.push_back("--crel");
2715     } else {
2716       D.Diag(diag::err_drv_unsupported_opt_for_target)
2717           << "-Wa,--crel" << D.getTargetTriple();
2718     }
2719   }
2720   if (ImplicitMapSyms)
2721     CmdArgs.push_back("-mmapsyms=implicit");
2722   if (Msa)
2723     CmdArgs.push_back("-mmsa");
2724   if (!UseRelaxRelocations)
2725     CmdArgs.push_back("-mrelax-relocations=no");
2726   if (UseNoExecStack)
2727     CmdArgs.push_back("-mnoexecstack");
2728   if (MipsTargetFeature != nullptr) {
2729     CmdArgs.push_back("-target-feature");
2730     CmdArgs.push_back(MipsTargetFeature);
2731   }
2732 
2733   for (const char *Feature : SparcTargetFeatures) {
2734     CmdArgs.push_back("-target-feature");
2735     CmdArgs.push_back(Feature);
2736   }
2737 
2738   // forward -fembed-bitcode to assmebler
2739   if (C.getDriver().embedBitcodeEnabled() ||
2740       C.getDriver().embedBitcodeMarkerOnly())
2741     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2742 
2743   if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2744     CmdArgs.push_back("-as-secure-log-file");
2745     CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2746   }
2747 }
2748 
ComplexArithmeticStr(LangOptions::ComplexRangeKind Range)2749 static std::string ComplexArithmeticStr(LangOptions::ComplexRangeKind Range) {
2750   return (Range == LangOptions::ComplexRangeKind::CX_None)
2751              ? ""
2752              : "-fcomplex-arithmetic=" + complexRangeKindToStr(Range);
2753 }
2754 
EmitComplexRangeDiag(const Driver & D,std::string str1,std::string str2)2755 static void EmitComplexRangeDiag(const Driver &D, std::string str1,
2756                                  std::string str2) {
2757   if (str1 != str2 && !str2.empty() && !str1.empty()) {
2758     D.Diag(clang::diag::warn_drv_overriding_option) << str1 << str2;
2759   }
2760 }
2761 
RenderFloatingPointOptions(const ToolChain & TC,const Driver & D,bool OFastEnabled,const ArgList & Args,ArgStringList & CmdArgs,const JobAction & JA)2762 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2763                                        bool OFastEnabled, const ArgList &Args,
2764                                        ArgStringList &CmdArgs,
2765                                        const JobAction &JA) {
2766   // List of veclibs which when used with -fveclib imply -fno-math-errno.
2767   constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2768                                                 llvm::StringLiteral("SLEEF")};
2769   bool NoMathErrnoWasImpliedByVecLib = false;
2770   const Arg *VecLibArg = nullptr;
2771   // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2772   const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2773 
2774   // Handle various floating point optimization flags, mapping them to the
2775   // appropriate LLVM code generation flags. This is complicated by several
2776   // "umbrella" flags, so we do this by stepping through the flags incrementally
2777   // adjusting what we think is enabled/disabled, then at the end setting the
2778   // LLVM flags based on the final state.
2779   bool HonorINFs = true;
2780   bool HonorNaNs = true;
2781   bool ApproxFunc = false;
2782   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2783   bool MathErrno = TC.IsMathErrnoDefault();
2784   bool AssociativeMath = false;
2785   bool ReciprocalMath = false;
2786   bool SignedZeros = true;
2787   bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2788   bool TrappingMathPresent = false; // Is trapping-math in args, and not
2789                                     // overriden by ffp-exception-behavior?
2790   bool RoundingFPMath = false;
2791   // -ffp-model values: strict, fast, precise
2792   StringRef FPModel = "";
2793   // -ffp-exception-behavior options: strict, maytrap, ignore
2794   StringRef FPExceptionBehavior = "";
2795   // -ffp-eval-method options: double, extended, source
2796   StringRef FPEvalMethod = "";
2797   llvm::DenormalMode DenormalFPMath =
2798       TC.getDefaultDenormalModeForType(Args, JA);
2799   llvm::DenormalMode DenormalFP32Math =
2800       TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2801 
2802   // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2803   // If one wasn't given by the user, don't pass it here.
2804   StringRef FPContract;
2805   StringRef LastSeenFfpContractOption;
2806   StringRef LastFpContractOverrideOption;
2807   bool SeenUnsafeMathModeOption = false;
2808   if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
2809       !JA.isOffloading(Action::OFK_HIP))
2810     FPContract = "on";
2811   bool StrictFPModel = false;
2812   StringRef Float16ExcessPrecision = "";
2813   StringRef BFloat16ExcessPrecision = "";
2814   LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_None;
2815   std::string ComplexRangeStr;
2816   std::string GccRangeComplexOption;
2817   std::string LastComplexRangeOption;
2818 
2819   auto setComplexRange = [&](LangOptions::ComplexRangeKind NewRange) {
2820     // Warn if user expects to perform full implementation of complex
2821     // multiplication or division in the presence of nnan or ninf flags.
2822     if (Range != NewRange)
2823       EmitComplexRangeDiag(D,
2824                            !GccRangeComplexOption.empty()
2825                                ? GccRangeComplexOption
2826                                : ComplexArithmeticStr(Range),
2827                            ComplexArithmeticStr(NewRange));
2828     Range = NewRange;
2829   };
2830 
2831   // Lambda to set fast-math options. This is also used by -ffp-model=fast
2832   auto applyFastMath = [&](bool Aggressive) {
2833     if (Aggressive) {
2834       HonorINFs = false;
2835       HonorNaNs = false;
2836       setComplexRange(LangOptions::ComplexRangeKind::CX_Basic);
2837     } else {
2838       HonorINFs = true;
2839       HonorNaNs = true;
2840       setComplexRange(LangOptions::ComplexRangeKind::CX_Promoted);
2841     }
2842     MathErrno = false;
2843     AssociativeMath = true;
2844     ReciprocalMath = true;
2845     ApproxFunc = true;
2846     SignedZeros = false;
2847     TrappingMath = false;
2848     RoundingFPMath = false;
2849     FPExceptionBehavior = "";
2850     FPContract = "fast";
2851     SeenUnsafeMathModeOption = true;
2852   };
2853 
2854   // Lambda to consolidate common handling for fp-contract
2855   auto restoreFPContractState = [&]() {
2856     // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2857     // For other targets, if the state has been changed by one of the
2858     // unsafe-math umbrella options a subsequent -fno-fast-math or
2859     // -fno-unsafe-math-optimizations option reverts to the last value seen for
2860     // the -ffp-contract option or "on" if we have not seen the -ffp-contract
2861     // option. If we have not seen an unsafe-math option or -ffp-contract,
2862     // we leave the FPContract state unchanged.
2863     if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
2864         !JA.isOffloading(Action::OFK_HIP)) {
2865       if (LastSeenFfpContractOption != "")
2866         FPContract = LastSeenFfpContractOption;
2867       else if (SeenUnsafeMathModeOption)
2868         FPContract = "on";
2869     }
2870     // In this case, we're reverting to the last explicit fp-contract option
2871     // or the platform default
2872     LastFpContractOverrideOption = "";
2873   };
2874 
2875   if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2876     CmdArgs.push_back("-mlimit-float-precision");
2877     CmdArgs.push_back(A->getValue());
2878   }
2879 
2880   for (const Arg *A : Args) {
2881     auto CheckMathErrnoForVecLib =
2882         llvm::make_scope_exit([&, MathErrnoBeforeArg = MathErrno] {
2883           if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
2884             ArgThatEnabledMathErrnoAfterVecLib = A;
2885         });
2886 
2887     switch (A->getOption().getID()) {
2888     // If this isn't an FP option skip the claim below
2889     default: continue;
2890 
2891     case options::OPT_fcx_limited_range:
2892       if (GccRangeComplexOption.empty()) {
2893         if (Range != LangOptions::ComplexRangeKind::CX_Basic)
2894           EmitComplexRangeDiag(D, renderComplexRangeOption(Range),
2895                                "-fcx-limited-range");
2896       } else {
2897         if (GccRangeComplexOption != "-fno-cx-limited-range")
2898           EmitComplexRangeDiag(D, GccRangeComplexOption, "-fcx-limited-range");
2899       }
2900       GccRangeComplexOption = "-fcx-limited-range";
2901       LastComplexRangeOption = A->getSpelling();
2902       Range = LangOptions::ComplexRangeKind::CX_Basic;
2903       break;
2904     case options::OPT_fno_cx_limited_range:
2905       if (GccRangeComplexOption.empty()) {
2906         EmitComplexRangeDiag(D, renderComplexRangeOption(Range),
2907                              "-fno-cx-limited-range");
2908       } else {
2909         if (GccRangeComplexOption != "-fcx-limited-range" &&
2910             GccRangeComplexOption != "-fno-cx-fortran-rules")
2911           EmitComplexRangeDiag(D, GccRangeComplexOption,
2912                                "-fno-cx-limited-range");
2913       }
2914       GccRangeComplexOption = "-fno-cx-limited-range";
2915       LastComplexRangeOption = A->getSpelling();
2916       Range = LangOptions::ComplexRangeKind::CX_Full;
2917       break;
2918     case options::OPT_fcx_fortran_rules:
2919       if (GccRangeComplexOption.empty())
2920         EmitComplexRangeDiag(D, renderComplexRangeOption(Range),
2921                              "-fcx-fortran-rules");
2922       else
2923         EmitComplexRangeDiag(D, GccRangeComplexOption, "-fcx-fortran-rules");
2924       GccRangeComplexOption = "-fcx-fortran-rules";
2925       LastComplexRangeOption = A->getSpelling();
2926       Range = LangOptions::ComplexRangeKind::CX_Improved;
2927       break;
2928     case options::OPT_fno_cx_fortran_rules:
2929       if (GccRangeComplexOption.empty()) {
2930         EmitComplexRangeDiag(D, renderComplexRangeOption(Range),
2931                              "-fno-cx-fortran-rules");
2932       } else {
2933         if (GccRangeComplexOption != "-fno-cx-limited-range")
2934           EmitComplexRangeDiag(D, GccRangeComplexOption,
2935                                "-fno-cx-fortran-rules");
2936       }
2937       GccRangeComplexOption = "-fno-cx-fortran-rules";
2938       LastComplexRangeOption = A->getSpelling();
2939       Range = LangOptions::ComplexRangeKind::CX_Full;
2940       break;
2941     case options::OPT_fcomplex_arithmetic_EQ: {
2942       LangOptions::ComplexRangeKind RangeVal;
2943       StringRef Val = A->getValue();
2944       if (Val == "full")
2945         RangeVal = LangOptions::ComplexRangeKind::CX_Full;
2946       else if (Val == "improved")
2947         RangeVal = LangOptions::ComplexRangeKind::CX_Improved;
2948       else if (Val == "promoted")
2949         RangeVal = LangOptions::ComplexRangeKind::CX_Promoted;
2950       else if (Val == "basic")
2951         RangeVal = LangOptions::ComplexRangeKind::CX_Basic;
2952       else {
2953         D.Diag(diag::err_drv_unsupported_option_argument)
2954             << A->getSpelling() << Val;
2955         break;
2956       }
2957       if (!GccRangeComplexOption.empty()) {
2958         if (GccRangeComplexOption != "-fcx-limited-range") {
2959           if (GccRangeComplexOption != "-fcx-fortran-rules") {
2960             if (RangeVal != LangOptions::ComplexRangeKind::CX_Improved)
2961               EmitComplexRangeDiag(D, GccRangeComplexOption,
2962                                    ComplexArithmeticStr(RangeVal));
2963           } else {
2964             EmitComplexRangeDiag(D, GccRangeComplexOption,
2965                                  ComplexArithmeticStr(RangeVal));
2966           }
2967         } else {
2968           if (RangeVal != LangOptions::ComplexRangeKind::CX_Basic)
2969             EmitComplexRangeDiag(D, GccRangeComplexOption,
2970                                  ComplexArithmeticStr(RangeVal));
2971         }
2972       }
2973       LastComplexRangeOption =
2974           Args.MakeArgString(A->getSpelling() + A->getValue());
2975       Range = RangeVal;
2976       break;
2977     }
2978     case options::OPT_ffp_model_EQ: {
2979       // If -ffp-model= is seen, reset to fno-fast-math
2980       HonorINFs = true;
2981       HonorNaNs = true;
2982       ApproxFunc = false;
2983       // Turning *off* -ffast-math restores the toolchain default.
2984       MathErrno = TC.IsMathErrnoDefault();
2985       AssociativeMath = false;
2986       ReciprocalMath = false;
2987       SignedZeros = true;
2988 
2989       StringRef Val = A->getValue();
2990       if (OFastEnabled && Val != "aggressive") {
2991         // Only -ffp-model=aggressive is compatible with -OFast, ignore.
2992         D.Diag(clang::diag::warn_drv_overriding_option)
2993             << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
2994         break;
2995       }
2996       StrictFPModel = false;
2997       if (!FPModel.empty() && FPModel != Val)
2998         D.Diag(clang::diag::warn_drv_overriding_option)
2999             << Args.MakeArgString("-ffp-model=" + FPModel)
3000             << Args.MakeArgString("-ffp-model=" + Val);
3001       if (Val == "fast") {
3002         FPModel = Val;
3003         applyFastMath(false);
3004         // applyFastMath sets fp-contract="fast"
3005         LastFpContractOverrideOption = "-ffp-model=fast";
3006       } else if (Val == "aggressive") {
3007         FPModel = Val;
3008         applyFastMath(true);
3009         // applyFastMath sets fp-contract="fast"
3010         LastFpContractOverrideOption = "-ffp-model=aggressive";
3011       } else if (Val == "precise") {
3012         FPModel = Val;
3013         FPContract = "on";
3014         LastFpContractOverrideOption = "-ffp-model=precise";
3015         setComplexRange(LangOptions::ComplexRangeKind::CX_Full);
3016       } else if (Val == "strict") {
3017         StrictFPModel = true;
3018         FPExceptionBehavior = "strict";
3019         FPModel = Val;
3020         FPContract = "off";
3021         LastFpContractOverrideOption = "-ffp-model=strict";
3022         TrappingMath = true;
3023         RoundingFPMath = true;
3024         setComplexRange(LangOptions::ComplexRangeKind::CX_Full);
3025       } else
3026         D.Diag(diag::err_drv_unsupported_option_argument)
3027             << A->getSpelling() << Val;
3028       LastComplexRangeOption = A->getSpelling();
3029       break;
3030     }
3031 
3032     // Options controlling individual features
3033     case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
3034     case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
3035     case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
3036     case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
3037     case options::OPT_fapprox_func:         ApproxFunc = true;        break;
3038     case options::OPT_fno_approx_func:      ApproxFunc = false;       break;
3039     case options::OPT_fmath_errno:          MathErrno = true;         break;
3040     case options::OPT_fno_math_errno:       MathErrno = false;        break;
3041     case options::OPT_fassociative_math:    AssociativeMath = true;   break;
3042     case options::OPT_fno_associative_math: AssociativeMath = false;  break;
3043     case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
3044     case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
3045     case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
3046     case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
3047     case options::OPT_ftrapping_math:
3048       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3049           FPExceptionBehavior != "strict")
3050         // Warn that previous value of option is overridden.
3051         D.Diag(clang::diag::warn_drv_overriding_option)
3052             << Args.MakeArgString("-ffp-exception-behavior=" +
3053                                   FPExceptionBehavior)
3054             << "-ftrapping-math";
3055       TrappingMath = true;
3056       TrappingMathPresent = true;
3057       FPExceptionBehavior = "strict";
3058       break;
3059     case options::OPT_fveclib:
3060       VecLibArg = A;
3061       NoMathErrnoWasImpliedByVecLib =
3062           llvm::is_contained(VecLibImpliesNoMathErrno, A->getValue());
3063       if (NoMathErrnoWasImpliedByVecLib)
3064         MathErrno = false;
3065       break;
3066     case options::OPT_fno_trapping_math:
3067       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3068           FPExceptionBehavior != "ignore")
3069         // Warn that previous value of option is overridden.
3070         D.Diag(clang::diag::warn_drv_overriding_option)
3071             << Args.MakeArgString("-ffp-exception-behavior=" +
3072                                   FPExceptionBehavior)
3073             << "-fno-trapping-math";
3074       TrappingMath = false;
3075       TrappingMathPresent = true;
3076       FPExceptionBehavior = "ignore";
3077       break;
3078 
3079     case options::OPT_frounding_math:
3080       RoundingFPMath = true;
3081       break;
3082 
3083     case options::OPT_fno_rounding_math:
3084       RoundingFPMath = false;
3085       break;
3086 
3087     case options::OPT_fdenormal_fp_math_EQ:
3088       DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
3089       DenormalFP32Math = DenormalFPMath;
3090       if (!DenormalFPMath.isValid()) {
3091         D.Diag(diag::err_drv_invalid_value)
3092             << A->getAsString(Args) << A->getValue();
3093       }
3094       break;
3095 
3096     case options::OPT_fdenormal_fp_math_f32_EQ:
3097       DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
3098       if (!DenormalFP32Math.isValid()) {
3099         D.Diag(diag::err_drv_invalid_value)
3100             << A->getAsString(Args) << A->getValue();
3101       }
3102       break;
3103 
3104     // Validate and pass through -ffp-contract option.
3105     case options::OPT_ffp_contract: {
3106       StringRef Val = A->getValue();
3107       if (Val == "fast" || Val == "on" || Val == "off" ||
3108           Val == "fast-honor-pragmas") {
3109         if (Val != FPContract && LastFpContractOverrideOption != "") {
3110           D.Diag(clang::diag::warn_drv_overriding_option)
3111               << LastFpContractOverrideOption
3112               << Args.MakeArgString("-ffp-contract=" + Val);
3113         }
3114 
3115         FPContract = Val;
3116         LastSeenFfpContractOption = Val;
3117         LastFpContractOverrideOption = "";
3118       } else
3119         D.Diag(diag::err_drv_unsupported_option_argument)
3120             << A->getSpelling() << Val;
3121       break;
3122     }
3123 
3124     // Validate and pass through -ffp-exception-behavior option.
3125     case options::OPT_ffp_exception_behavior_EQ: {
3126       StringRef Val = A->getValue();
3127       if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3128           FPExceptionBehavior != Val)
3129         // Warn that previous value of option is overridden.
3130         D.Diag(clang::diag::warn_drv_overriding_option)
3131             << Args.MakeArgString("-ffp-exception-behavior=" +
3132                                   FPExceptionBehavior)
3133             << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3134       TrappingMath = TrappingMathPresent = false;
3135       if (Val == "ignore" || Val == "maytrap")
3136         FPExceptionBehavior = Val;
3137       else if (Val == "strict") {
3138         FPExceptionBehavior = Val;
3139         TrappingMath = TrappingMathPresent = true;
3140       } else
3141         D.Diag(diag::err_drv_unsupported_option_argument)
3142             << A->getSpelling() << Val;
3143       break;
3144     }
3145 
3146     // Validate and pass through -ffp-eval-method option.
3147     case options::OPT_ffp_eval_method_EQ: {
3148       StringRef Val = A->getValue();
3149       if (Val == "double" || Val == "extended" || Val == "source")
3150         FPEvalMethod = Val;
3151       else
3152         D.Diag(diag::err_drv_unsupported_option_argument)
3153             << A->getSpelling() << Val;
3154       break;
3155     }
3156 
3157     case options::OPT_fexcess_precision_EQ: {
3158       StringRef Val = A->getValue();
3159       const llvm::Triple::ArchType Arch = TC.getArch();
3160       if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3161         if (Val == "standard" || Val == "fast")
3162           Float16ExcessPrecision = Val;
3163         // To make it GCC compatible, allow the value of "16" which
3164         // means disable excess precision, the same meaning than clang's
3165         // equivalent value "none".
3166         else if (Val == "16")
3167           Float16ExcessPrecision = "none";
3168         else
3169           D.Diag(diag::err_drv_unsupported_option_argument)
3170               << A->getSpelling() << Val;
3171       } else {
3172         if (!(Val == "standard" || Val == "fast"))
3173           D.Diag(diag::err_drv_unsupported_option_argument)
3174               << A->getSpelling() << Val;
3175       }
3176       BFloat16ExcessPrecision = Float16ExcessPrecision;
3177       break;
3178     }
3179     case options::OPT_ffinite_math_only:
3180       HonorINFs = false;
3181       HonorNaNs = false;
3182       break;
3183     case options::OPT_fno_finite_math_only:
3184       HonorINFs = true;
3185       HonorNaNs = true;
3186       break;
3187 
3188     case options::OPT_funsafe_math_optimizations:
3189       AssociativeMath = true;
3190       ReciprocalMath = true;
3191       SignedZeros = false;
3192       ApproxFunc = true;
3193       TrappingMath = false;
3194       FPExceptionBehavior = "";
3195       FPContract = "fast";
3196       LastFpContractOverrideOption = "-funsafe-math-optimizations";
3197       SeenUnsafeMathModeOption = true;
3198       break;
3199     case options::OPT_fno_unsafe_math_optimizations:
3200       AssociativeMath = false;
3201       ReciprocalMath = false;
3202       SignedZeros = true;
3203       ApproxFunc = false;
3204       restoreFPContractState();
3205       break;
3206 
3207     case options::OPT_Ofast:
3208       // If -Ofast is the optimization level, then -ffast-math should be enabled
3209       if (!OFastEnabled)
3210         continue;
3211       [[fallthrough]];
3212     case options::OPT_ffast_math:
3213       applyFastMath(true);
3214       LastComplexRangeOption = A->getSpelling();
3215       if (A->getOption().getID() == options::OPT_Ofast)
3216         LastFpContractOverrideOption = "-Ofast";
3217       else
3218         LastFpContractOverrideOption = "-ffast-math";
3219       break;
3220     case options::OPT_fno_fast_math:
3221       HonorINFs = true;
3222       HonorNaNs = true;
3223       // Turning on -ffast-math (with either flag) removes the need for
3224       // MathErrno. However, turning *off* -ffast-math merely restores the
3225       // toolchain default (which may be false).
3226       MathErrno = TC.IsMathErrnoDefault();
3227       AssociativeMath = false;
3228       ReciprocalMath = false;
3229       ApproxFunc = false;
3230       SignedZeros = true;
3231       restoreFPContractState();
3232       // If the last specified option related to complex range is not
3233       // -ffast-math or -ffp-model=, emit warning.
3234       if (LastComplexRangeOption != "-ffast-math" &&
3235           LastComplexRangeOption != "-ffp-model=" &&
3236           Range != LangOptions::ComplexRangeKind::CX_Full)
3237         EmitComplexRangeDiag(D, LastComplexRangeOption, "-fno-fast-math");
3238       Range = LangOptions::ComplexRangeKind::CX_None;
3239       LastComplexRangeOption = "";
3240       GccRangeComplexOption = "";
3241       LastFpContractOverrideOption = "";
3242       break;
3243     } // End switch (A->getOption().getID())
3244 
3245     // The StrictFPModel local variable is needed to report warnings
3246     // in the way we intend. If -ffp-model=strict has been used, we
3247     // want to report a warning for the next option encountered that
3248     // takes us out of the settings described by fp-model=strict, but
3249     // we don't want to continue issuing warnings for other conflicting
3250     // options after that.
3251     if (StrictFPModel) {
3252       // If -ffp-model=strict has been specified on command line but
3253       // subsequent options conflict then emit warning diagnostic.
3254       if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3255           SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3256           FPContract == "off")
3257         // OK: Current Arg doesn't conflict with -ffp-model=strict
3258         ;
3259       else {
3260         StrictFPModel = false;
3261         FPModel = "";
3262         // The warning for -ffp-contract would have been reported by the
3263         // OPT_ffp_contract_EQ handler above. A special check here is needed
3264         // to avoid duplicating the warning.
3265         auto RHS = (A->getNumValues() == 0)
3266                        ? A->getSpelling()
3267                        : Args.MakeArgString(A->getSpelling() + A->getValue());
3268         if (A->getSpelling() != "-ffp-contract=") {
3269           if (RHS != "-ffp-model=strict")
3270             D.Diag(clang::diag::warn_drv_overriding_option)
3271                 << "-ffp-model=strict" << RHS;
3272         }
3273       }
3274     }
3275 
3276     // If we handled this option claim it
3277     A->claim();
3278   }
3279 
3280   if (!HonorINFs)
3281     CmdArgs.push_back("-menable-no-infs");
3282 
3283   if (!HonorNaNs)
3284     CmdArgs.push_back("-menable-no-nans");
3285 
3286   if (ApproxFunc)
3287     CmdArgs.push_back("-fapprox-func");
3288 
3289   if (MathErrno) {
3290     CmdArgs.push_back("-fmath-errno");
3291     if (NoMathErrnoWasImpliedByVecLib)
3292       D.Diag(clang::diag::warn_drv_math_errno_enabled_after_veclib)
3293           << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3294           << VecLibArg->getAsString(Args);
3295   }
3296 
3297  if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3298      !TrappingMath)
3299     CmdArgs.push_back("-funsafe-math-optimizations");
3300 
3301   if (!SignedZeros)
3302     CmdArgs.push_back("-fno-signed-zeros");
3303 
3304   if (AssociativeMath && !SignedZeros && !TrappingMath)
3305     CmdArgs.push_back("-mreassociate");
3306 
3307   if (ReciprocalMath)
3308     CmdArgs.push_back("-freciprocal-math");
3309 
3310   if (TrappingMath) {
3311     // FP Exception Behavior is also set to strict
3312     assert(FPExceptionBehavior == "strict");
3313   }
3314 
3315   // The default is IEEE.
3316   if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3317     llvm::SmallString<64> DenormFlag;
3318     llvm::raw_svector_ostream ArgStr(DenormFlag);
3319     ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3320     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3321   }
3322 
3323   // Add f32 specific denormal mode flag if it's different.
3324   if (DenormalFP32Math != DenormalFPMath) {
3325     llvm::SmallString<64> DenormFlag;
3326     llvm::raw_svector_ostream ArgStr(DenormFlag);
3327     ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3328     CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3329   }
3330 
3331   if (!FPContract.empty())
3332     CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3333 
3334   if (RoundingFPMath)
3335     CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3336   else
3337     CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3338 
3339   if (!FPExceptionBehavior.empty())
3340     CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3341                       FPExceptionBehavior));
3342 
3343   if (!FPEvalMethod.empty())
3344     CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3345 
3346   if (!Float16ExcessPrecision.empty())
3347     CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3348                                          Float16ExcessPrecision));
3349   if (!BFloat16ExcessPrecision.empty())
3350     CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3351                                          BFloat16ExcessPrecision));
3352 
3353   StringRef Recip = parseMRecipOption(D.getDiags(), Args);
3354   if (!Recip.empty())
3355     CmdArgs.push_back(Args.MakeArgString("-mrecip=" + Recip));
3356 
3357   // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3358   // individual features enabled by -ffast-math instead of the option itself as
3359   // that's consistent with gcc's behaviour.
3360   if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3361       ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3362     CmdArgs.push_back("-ffast-math");
3363 
3364   // Handle __FINITE_MATH_ONLY__ similarly.
3365   // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3366   // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3367   // -menable-no-nans are set by the user.
3368   bool shouldAddFiniteMathOnly = false;
3369   if (!HonorINFs && !HonorNaNs) {
3370     shouldAddFiniteMathOnly = true;
3371   } else {
3372     bool InfValues = true;
3373     bool NanValues = true;
3374     for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {
3375       StringRef ArgValue = Arg->getValue();
3376       if (ArgValue == "-menable-no-nans")
3377         NanValues = false;
3378       else if (ArgValue == "-menable-no-infs")
3379         InfValues = false;
3380     }
3381     if (!NanValues && !InfValues)
3382       shouldAddFiniteMathOnly = true;
3383   }
3384   if (shouldAddFiniteMathOnly) {
3385     CmdArgs.push_back("-ffinite-math-only");
3386   }
3387   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3388     CmdArgs.push_back("-mfpmath");
3389     CmdArgs.push_back(A->getValue());
3390   }
3391 
3392   // Disable a codegen optimization for floating-point casts.
3393   if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3394                    options::OPT_fstrict_float_cast_overflow, false))
3395     CmdArgs.push_back("-fno-strict-float-cast-overflow");
3396 
3397   if (Range != LangOptions::ComplexRangeKind::CX_None)
3398     ComplexRangeStr = renderComplexRangeOption(Range);
3399   if (!ComplexRangeStr.empty()) {
3400     CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3401     if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3402       CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
3403                                            complexRangeKindToStr(Range)));
3404   }
3405   if (Args.hasArg(options::OPT_fcx_limited_range))
3406     CmdArgs.push_back("-fcx-limited-range");
3407   if (Args.hasArg(options::OPT_fcx_fortran_rules))
3408     CmdArgs.push_back("-fcx-fortran-rules");
3409   if (Args.hasArg(options::OPT_fno_cx_limited_range))
3410     CmdArgs.push_back("-fno-cx-limited-range");
3411   if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3412     CmdArgs.push_back("-fno-cx-fortran-rules");
3413 }
3414 
RenderAnalyzerOptions(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple,const InputInfo & Input)3415 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3416                                   const llvm::Triple &Triple,
3417                                   const InputInfo &Input) {
3418   // Add default argument set.
3419   if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3420     CmdArgs.push_back("-analyzer-checker=core");
3421     CmdArgs.push_back("-analyzer-checker=apiModeling");
3422 
3423     if (!Triple.isWindowsMSVCEnvironment()) {
3424       CmdArgs.push_back("-analyzer-checker=unix");
3425     } else {
3426       // Enable "unix" checkers that also work on Windows.
3427       CmdArgs.push_back("-analyzer-checker=unix.API");
3428       CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3429       CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3430       CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3431       CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3432       CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3433     }
3434 
3435     // Disable some unix checkers for PS4/PS5.
3436     if (Triple.isPS()) {
3437       CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3438       CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3439     }
3440 
3441     if (Triple.isOSDarwin()) {
3442       CmdArgs.push_back("-analyzer-checker=osx");
3443       CmdArgs.push_back(
3444           "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3445     }
3446     else if (Triple.isOSFuchsia())
3447       CmdArgs.push_back("-analyzer-checker=fuchsia");
3448 
3449     CmdArgs.push_back("-analyzer-checker=deadcode");
3450 
3451     if (types::isCXX(Input.getType()))
3452       CmdArgs.push_back("-analyzer-checker=cplusplus");
3453 
3454     if (!Triple.isPS()) {
3455       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3456       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3457       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3458       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3459       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3460       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3461     }
3462 
3463     // Default nullability checks.
3464     CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3465     CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3466   }
3467 
3468   // Set the output format. The default is plist, for (lame) historical reasons.
3469   CmdArgs.push_back("-analyzer-output");
3470   if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3471     CmdArgs.push_back(A->getValue());
3472   else
3473     CmdArgs.push_back("plist");
3474 
3475   // Disable the presentation of standard compiler warnings when using
3476   // --analyze.  We only want to show static analyzer diagnostics or frontend
3477   // errors.
3478   CmdArgs.push_back("-w");
3479 
3480   // Add -Xanalyzer arguments when running as analyzer.
3481   Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3482 }
3483 
isValidSymbolName(StringRef S)3484 static bool isValidSymbolName(StringRef S) {
3485   if (S.empty())
3486     return false;
3487 
3488   if (std::isdigit(S[0]))
3489     return false;
3490 
3491   return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3492 }
3493 
RenderSSPOptions(const Driver & D,const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext)3494 static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3495                              const ArgList &Args, ArgStringList &CmdArgs,
3496                              bool KernelOrKext) {
3497   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3498 
3499   // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3500   // doesn't even have a stack!
3501   if (EffectiveTriple.isNVPTX())
3502     return;
3503 
3504   // -stack-protector=0 is default.
3505   LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3506   LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3507       TC.GetDefaultStackProtectorLevel(KernelOrKext);
3508 
3509   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3510                                options::OPT_fstack_protector_all,
3511                                options::OPT_fstack_protector_strong,
3512                                options::OPT_fstack_protector)) {
3513     if (A->getOption().matches(options::OPT_fstack_protector))
3514       StackProtectorLevel =
3515           std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3516     else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3517       StackProtectorLevel = LangOptions::SSPStrong;
3518     else if (A->getOption().matches(options::OPT_fstack_protector_all))
3519       StackProtectorLevel = LangOptions::SSPReq;
3520 
3521     if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3522       D.Diag(diag::warn_drv_unsupported_option_for_target)
3523           << A->getSpelling() << EffectiveTriple.getTriple();
3524       StackProtectorLevel = DefaultStackProtectorLevel;
3525     }
3526   } else {
3527     StackProtectorLevel = DefaultStackProtectorLevel;
3528   }
3529 
3530   if (StackProtectorLevel) {
3531     CmdArgs.push_back("-stack-protector");
3532     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3533   }
3534 
3535   // --param ssp-buffer-size=
3536   for (const Arg *A : Args.filtered(options::OPT__param)) {
3537     StringRef Str(A->getValue());
3538     if (Str.consume_front("ssp-buffer-size=")) {
3539       if (StackProtectorLevel) {
3540         CmdArgs.push_back("-stack-protector-buffer-size");
3541         // FIXME: Verify the argument is a valid integer.
3542         CmdArgs.push_back(Args.MakeArgString(Str));
3543       }
3544       A->claim();
3545     }
3546   }
3547 
3548   const std::string &TripleStr = EffectiveTriple.getTriple();
3549   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3550     StringRef Value = A->getValue();
3551     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3552         !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3553         !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3554       D.Diag(diag::err_drv_unsupported_opt_for_target)
3555           << A->getAsString(Args) << TripleStr;
3556     if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3557          EffectiveTriple.isThumb()) &&
3558         Value != "tls" && Value != "global") {
3559       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3560           << A->getOption().getName() << Value << "tls global";
3561       return;
3562     }
3563     if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3564         Value == "tls") {
3565       if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3566         D.Diag(diag::err_drv_ssp_missing_offset_argument)
3567             << A->getAsString(Args);
3568         return;
3569       }
3570       // Check whether the target subarch supports the hardware TLS register
3571       if (!arm::isHardTPSupported(EffectiveTriple)) {
3572         D.Diag(diag::err_target_unsupported_tp_hard)
3573             << EffectiveTriple.getArchName();
3574         return;
3575       }
3576       // Check whether the user asked for something other than -mtp=cp15
3577       if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3578         StringRef Value = A->getValue();
3579         if (Value != "cp15") {
3580           D.Diag(diag::err_drv_argument_not_allowed_with)
3581               << A->getAsString(Args) << "-mstack-protector-guard=tls";
3582           return;
3583         }
3584       }
3585       CmdArgs.push_back("-target-feature");
3586       CmdArgs.push_back("+read-tp-tpidruro");
3587     }
3588     if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3589       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3590           << A->getOption().getName() << Value << "sysreg global";
3591       return;
3592     }
3593     if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3594       if (Value != "tls" && Value != "global") {
3595         D.Diag(diag::err_drv_invalid_value_with_suggestion)
3596             << A->getOption().getName() << Value << "tls global";
3597         return;
3598       }
3599       if (Value == "tls") {
3600         if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3601           D.Diag(diag::err_drv_ssp_missing_offset_argument)
3602               << A->getAsString(Args);
3603           return;
3604         }
3605       }
3606     }
3607     A->render(Args, CmdArgs);
3608   }
3609 
3610   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3611     StringRef Value = A->getValue();
3612     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3613         !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3614         !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3615       D.Diag(diag::err_drv_unsupported_opt_for_target)
3616           << A->getAsString(Args) << TripleStr;
3617     int Offset;
3618     if (Value.getAsInteger(10, Offset)) {
3619       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3620       return;
3621     }
3622     if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3623         (Offset < 0 || Offset > 0xfffff)) {
3624       D.Diag(diag::err_drv_invalid_int_value)
3625           << A->getOption().getName() << Value;
3626       return;
3627     }
3628     A->render(Args, CmdArgs);
3629   }
3630 
3631   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3632     StringRef Value = A->getValue();
3633     if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3634         !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3635       D.Diag(diag::err_drv_unsupported_opt_for_target)
3636           << A->getAsString(Args) << TripleStr;
3637     if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3638       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3639           << A->getOption().getName() << Value << "fs gs";
3640       return;
3641     }
3642     if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3643       D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3644       return;
3645     }
3646     if (EffectiveTriple.isRISCV() && Value != "tp") {
3647       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3648           << A->getOption().getName() << Value << "tp";
3649       return;
3650     }
3651     if (EffectiveTriple.isPPC64() && Value != "r13") {
3652       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3653           << A->getOption().getName() << Value << "r13";
3654       return;
3655     }
3656     if (EffectiveTriple.isPPC32() && Value != "r2") {
3657       D.Diag(diag::err_drv_invalid_value_with_suggestion)
3658           << A->getOption().getName() << Value << "r2";
3659       return;
3660     }
3661     A->render(Args, CmdArgs);
3662   }
3663 
3664   if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3665     StringRef Value = A->getValue();
3666     if (!isValidSymbolName(Value)) {
3667       D.Diag(diag::err_drv_argument_only_allowed_with)
3668           << A->getOption().getName() << "legal symbol name";
3669       return;
3670     }
3671     A->render(Args, CmdArgs);
3672   }
3673 }
3674 
RenderSCPOptions(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)3675 static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3676                              ArgStringList &CmdArgs) {
3677   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3678 
3679   if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3680       !EffectiveTriple.isOSFuchsia())
3681     return;
3682 
3683   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3684       !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3685       !EffectiveTriple.isRISCV())
3686     return;
3687 
3688   Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3689                     options::OPT_fno_stack_clash_protection);
3690 }
3691 
RenderTrivialAutoVarInitOptions(const Driver & D,const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)3692 static void RenderTrivialAutoVarInitOptions(const Driver &D,
3693                                             const ToolChain &TC,
3694                                             const ArgList &Args,
3695                                             ArgStringList &CmdArgs) {
3696   auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3697   StringRef TrivialAutoVarInit = "";
3698 
3699   for (const Arg *A : Args) {
3700     switch (A->getOption().getID()) {
3701     default:
3702       continue;
3703     case options::OPT_ftrivial_auto_var_init: {
3704       A->claim();
3705       StringRef Val = A->getValue();
3706       if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3707         TrivialAutoVarInit = Val;
3708       else
3709         D.Diag(diag::err_drv_unsupported_option_argument)
3710             << A->getSpelling() << Val;
3711       break;
3712     }
3713     }
3714   }
3715 
3716   if (TrivialAutoVarInit.empty())
3717     switch (DefaultTrivialAutoVarInit) {
3718     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3719       break;
3720     case LangOptions::TrivialAutoVarInitKind::Pattern:
3721       TrivialAutoVarInit = "pattern";
3722       break;
3723     case LangOptions::TrivialAutoVarInitKind::Zero:
3724       TrivialAutoVarInit = "zero";
3725       break;
3726     }
3727 
3728   if (!TrivialAutoVarInit.empty()) {
3729     CmdArgs.push_back(
3730         Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3731   }
3732 
3733   if (Arg *A =
3734           Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3735     if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3736         StringRef(
3737             Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3738             "uninitialized")
3739       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3740     A->claim();
3741     StringRef Val = A->getValue();
3742     if (std::stoi(Val.str()) <= 0)
3743       D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3744     CmdArgs.push_back(
3745         Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3746   }
3747 
3748   if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3749     if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3750         StringRef(
3751             Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3752             "uninitialized")
3753       D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3754     A->claim();
3755     StringRef Val = A->getValue();
3756     if (std::stoi(Val.str()) <= 0)
3757       D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3758     CmdArgs.push_back(
3759         Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
3760   }
3761 }
3762 
RenderOpenCLOptions(const ArgList & Args,ArgStringList & CmdArgs,types::ID InputType)3763 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3764                                 types::ID InputType) {
3765   // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3766   // for denormal flushing handling based on the target.
3767   const unsigned ForwardedArguments[] = {
3768       options::OPT_cl_opt_disable,
3769       options::OPT_cl_strict_aliasing,
3770       options::OPT_cl_single_precision_constant,
3771       options::OPT_cl_finite_math_only,
3772       options::OPT_cl_kernel_arg_info,
3773       options::OPT_cl_unsafe_math_optimizations,
3774       options::OPT_cl_fast_relaxed_math,
3775       options::OPT_cl_mad_enable,
3776       options::OPT_cl_no_signed_zeros,
3777       options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3778       options::OPT_cl_uniform_work_group_size
3779   };
3780 
3781   if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3782     std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3783     CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3784   } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3785     std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3786     CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3787   }
3788 
3789   if (Args.hasArg(options::OPT_cl_finite_math_only)) {
3790     CmdArgs.push_back("-menable-no-infs");
3791     CmdArgs.push_back("-menable-no-nans");
3792   }
3793 
3794   for (const auto &Arg : ForwardedArguments)
3795     if (const auto *A = Args.getLastArg(Arg))
3796       CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3797 
3798   // Only add the default headers if we are compiling OpenCL sources.
3799   if ((types::isOpenCL(InputType) ||
3800        (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3801       !Args.hasArg(options::OPT_cl_no_stdinc)) {
3802     CmdArgs.push_back("-finclude-default-header");
3803     CmdArgs.push_back("-fdeclare-opencl-builtins");
3804   }
3805 }
3806 
RenderHLSLOptions(const ArgList & Args,ArgStringList & CmdArgs,types::ID InputType)3807 static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3808                               types::ID InputType) {
3809   const unsigned ForwardedArguments[] = {
3810       options::OPT_dxil_validator_version,
3811       options::OPT_res_may_alias,
3812       options::OPT_D,
3813       options::OPT_I,
3814       options::OPT_O,
3815       options::OPT_emit_llvm,
3816       options::OPT_emit_obj,
3817       options::OPT_disable_llvm_passes,
3818       options::OPT_fnative_half_type,
3819       options::OPT_hlsl_entrypoint,
3820       options::OPT_fdx_rootsignature_version};
3821   if (!types::isHLSL(InputType))
3822     return;
3823   for (const auto &Arg : ForwardedArguments)
3824     if (const auto *A = Args.getLastArg(Arg))
3825       A->renderAsInput(Args, CmdArgs);
3826   // Add the default headers if dxc_no_stdinc is not set.
3827   if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3828       !Args.hasArg(options::OPT_nostdinc))
3829     CmdArgs.push_back("-finclude-default-header");
3830 }
3831 
RenderOpenACCOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,types::ID InputType)3832 static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3833                                  ArgStringList &CmdArgs, types::ID InputType) {
3834   if (!Args.hasArg(options::OPT_fopenacc))
3835     return;
3836 
3837   CmdArgs.push_back("-fopenacc");
3838 
3839   if (Arg *A = Args.getLastArg(options::OPT_openacc_macro_override)) {
3840     StringRef Value = A->getValue();
3841     int Version;
3842     if (!Value.getAsInteger(10, Version))
3843       A->renderAsInput(Args, CmdArgs);
3844     else
3845       D.Diag(diag::err_drv_clang_unsupported) << Value;
3846   }
3847 }
3848 
RenderBuiltinOptions(const ToolChain & TC,const llvm::Triple & T,const ArgList & Args,ArgStringList & CmdArgs)3849 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3850                                  const ArgList &Args, ArgStringList &CmdArgs) {
3851   // -fbuiltin is default unless -mkernel is used.
3852   bool UseBuiltins =
3853       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3854                    !Args.hasArg(options::OPT_mkernel));
3855   if (!UseBuiltins)
3856     CmdArgs.push_back("-fno-builtin");
3857 
3858   // -ffreestanding implies -fno-builtin.
3859   if (Args.hasArg(options::OPT_ffreestanding))
3860     UseBuiltins = false;
3861 
3862   // Process the -fno-builtin-* options.
3863   for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
3864     A->claim();
3865 
3866     // If -fno-builtin is specified, then there's no need to pass the option to
3867     // the frontend.
3868     if (UseBuiltins)
3869       A->render(Args, CmdArgs);
3870   }
3871 }
3872 
getDefaultModuleCachePath(SmallVectorImpl<char> & Result)3873 bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3874   if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
3875     Twine Path{Str};
3876     Path.toVector(Result);
3877     return Path.getSingleStringRef() != "";
3878   }
3879   if (llvm::sys::path::cache_directory(Result)) {
3880     llvm::sys::path::append(Result, "clang");
3881     llvm::sys::path::append(Result, "ModuleCache");
3882     return true;
3883   }
3884   return false;
3885 }
3886 
3887 llvm::SmallString<256>
getCXX20NamedModuleOutputPath(const ArgList & Args,const char * BaseInput)3888 clang::driver::tools::getCXX20NamedModuleOutputPath(const ArgList &Args,
3889                                                     const char *BaseInput) {
3890   if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
3891     return StringRef(ModuleOutputEQ->getValue());
3892 
3893   SmallString<256> OutputPath;
3894   if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
3895       FinalOutput && Args.hasArg(options::OPT_c))
3896     OutputPath = FinalOutput->getValue();
3897   else
3898     OutputPath = BaseInput;
3899 
3900   const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
3901   llvm::sys::path::replace_extension(OutputPath, Extension);
3902   return OutputPath;
3903 }
3904 
RenderModulesOptions(Compilation & C,const Driver & D,const ArgList & Args,const InputInfo & Input,const InputInfo & Output,bool HaveStd20,ArgStringList & CmdArgs)3905 static bool RenderModulesOptions(Compilation &C, const Driver &D,
3906                                  const ArgList &Args, const InputInfo &Input,
3907                                  const InputInfo &Output, bool HaveStd20,
3908                                  ArgStringList &CmdArgs) {
3909   bool IsCXX = types::isCXX(Input.getType());
3910   bool HaveStdCXXModules = IsCXX && HaveStd20;
3911   bool HaveModules = HaveStdCXXModules;
3912 
3913   // -fmodules enables the use of precompiled modules (off by default).
3914   // Users can pass -fno-cxx-modules to turn off modules support for
3915   // C++/Objective-C++ programs.
3916   bool HaveClangModules = false;
3917   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3918     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3919                                      options::OPT_fno_cxx_modules, true);
3920     if (AllowedInCXX || !IsCXX) {
3921       CmdArgs.push_back("-fmodules");
3922       HaveClangModules = true;
3923     }
3924   }
3925 
3926   HaveModules |= HaveClangModules;
3927 
3928   // -fmodule-maps enables implicit reading of module map files. By default,
3929   // this is enabled if we are using Clang's flavor of precompiled modules.
3930   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3931                    options::OPT_fno_implicit_module_maps, HaveClangModules))
3932     CmdArgs.push_back("-fimplicit-module-maps");
3933 
3934   // -fmodules-decluse checks that modules used are declared so (off by default)
3935   Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
3936                     options::OPT_fno_modules_decluse);
3937 
3938   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3939   // all #included headers are part of modules.
3940   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3941                    options::OPT_fno_modules_strict_decluse, false))
3942     CmdArgs.push_back("-fmodules-strict-decluse");
3943 
3944   Args.addOptOutFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,
3945                      options::OPT_fno_modulemap_allow_subdirectory_search);
3946 
3947   // -fno-implicit-modules turns off implicitly compiling modules on demand.
3948   bool ImplicitModules = false;
3949   if (!Args.hasFlag(options::OPT_fimplicit_modules,
3950                     options::OPT_fno_implicit_modules, HaveClangModules)) {
3951     if (HaveModules)
3952       CmdArgs.push_back("-fno-implicit-modules");
3953   } else if (HaveModules) {
3954     ImplicitModules = true;
3955     // -fmodule-cache-path specifies where our implicitly-built module files
3956     // should be written.
3957     SmallString<128> Path;
3958     if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3959       Path = A->getValue();
3960 
3961     bool HasPath = true;
3962     if (C.isForDiagnostics()) {
3963       // When generating crash reports, we want to emit the modules along with
3964       // the reproduction sources, so we ignore any provided module path.
3965       Path = Output.getFilename();
3966       llvm::sys::path::replace_extension(Path, ".cache");
3967       llvm::sys::path::append(Path, "modules");
3968     } else if (Path.empty()) {
3969       // No module path was provided: use the default.
3970       HasPath = Driver::getDefaultModuleCachePath(Path);
3971     }
3972 
3973     // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3974     // That being said, that failure is unlikely and not caching is harmless.
3975     if (HasPath) {
3976       const char Arg[] = "-fmodules-cache-path=";
3977       Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3978       CmdArgs.push_back(Args.MakeArgString(Path));
3979     }
3980   }
3981 
3982   if (HaveModules) {
3983     if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3984                      options::OPT_fno_prebuilt_implicit_modules, false))
3985       CmdArgs.push_back("-fprebuilt-implicit-modules");
3986     if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3987                      options::OPT_fno_modules_validate_input_files_content,
3988                      false))
3989       CmdArgs.push_back("-fvalidate-ast-input-files-content");
3990   }
3991 
3992   // -fmodule-name specifies the module that is currently being built (or
3993   // used for header checking by -fmodule-maps).
3994   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3995 
3996   // -fmodule-map-file can be used to specify files containing module
3997   // definitions.
3998   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3999 
4000   // -fbuiltin-module-map can be used to load the clang
4001   // builtin headers modulemap file.
4002   if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
4003     SmallString<128> BuiltinModuleMap(D.ResourceDir);
4004     llvm::sys::path::append(BuiltinModuleMap, "include");
4005     llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
4006     if (llvm::sys::fs::exists(BuiltinModuleMap))
4007       CmdArgs.push_back(
4008           Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
4009   }
4010 
4011   // The -fmodule-file=<name>=<file> form specifies the mapping of module
4012   // names to precompiled module files (the module is loaded only if used).
4013   // The -fmodule-file=<file> form can be used to unconditionally load
4014   // precompiled module files (whether used or not).
4015   if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4016     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4017 
4018     // -fprebuilt-module-path specifies where to load the prebuilt module files.
4019     for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
4020       CmdArgs.push_back(Args.MakeArgString(
4021           std::string("-fprebuilt-module-path=") + A->getValue()));
4022       A->claim();
4023     }
4024   } else
4025     Args.ClaimAllArgs(options::OPT_fmodule_file);
4026 
4027   // When building modules and generating crashdumps, we need to dump a module
4028   // dependency VFS alongside the output.
4029   if (HaveClangModules && C.isForDiagnostics()) {
4030     SmallString<128> VFSDir(Output.getFilename());
4031     llvm::sys::path::replace_extension(VFSDir, ".cache");
4032     // Add the cache directory as a temp so the crash diagnostics pick it up.
4033     C.addTempFile(Args.MakeArgString(VFSDir));
4034 
4035     llvm::sys::path::append(VFSDir, "vfs");
4036     CmdArgs.push_back("-module-dependency-dir");
4037     CmdArgs.push_back(Args.MakeArgString(VFSDir));
4038   }
4039 
4040   if (HaveClangModules)
4041     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4042 
4043   // Pass through all -fmodules-ignore-macro arguments.
4044   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4045   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4046   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4047 
4048   if (HaveClangModules) {
4049     Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4050 
4051     if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4052       if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4053         D.Diag(diag::err_drv_argument_not_allowed_with)
4054             << A->getAsString(Args) << "-fbuild-session-timestamp";
4055 
4056       llvm::sys::fs::file_status Status;
4057       if (llvm::sys::fs::status(A->getValue(), Status))
4058         D.Diag(diag::err_drv_no_such_file) << A->getValue();
4059       CmdArgs.push_back(Args.MakeArgString(
4060           "-fbuild-session-timestamp=" +
4061           Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4062                     Status.getLastModificationTime().time_since_epoch())
4063                     .count())));
4064     }
4065 
4066     if (Args.getLastArg(
4067             options::OPT_fmodules_validate_once_per_build_session)) {
4068       if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4069                            options::OPT_fbuild_session_file))
4070         D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4071 
4072       Args.AddLastArg(CmdArgs,
4073                       options::OPT_fmodules_validate_once_per_build_session);
4074     }
4075 
4076     if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4077                      options::OPT_fno_modules_validate_system_headers,
4078                      ImplicitModules))
4079       CmdArgs.push_back("-fmodules-validate-system-headers");
4080 
4081     Args.AddLastArg(CmdArgs,
4082                     options::OPT_fmodules_disable_diagnostic_validation);
4083   } else {
4084     Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4085     Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4086     Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4087     Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4088     Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4089     Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4090   }
4091 
4092   // FIXME: We provisionally don't check ODR violations for decls in the global
4093   // module fragment.
4094   CmdArgs.push_back("-fskip-odr-check-in-gmf");
4095 
4096   if (Args.hasArg(options::OPT_modules_reduced_bmi) &&
4097       (Input.getType() == driver::types::TY_CXXModule ||
4098        Input.getType() == driver::types::TY_PP_CXXModule)) {
4099     CmdArgs.push_back("-fmodules-reduced-bmi");
4100 
4101     if (Args.hasArg(options::OPT_fmodule_output_EQ))
4102       Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4103     else {
4104       if (Args.hasArg(options::OPT__precompile) &&
4105           (!Args.hasArg(options::OPT_o) ||
4106            Args.getLastArg(options::OPT_o)->getValue() ==
4107                getCXX20NamedModuleOutputPath(Args, Input.getBaseInput()))) {
4108         D.Diag(diag::err_drv_reduced_module_output_overrided);
4109       }
4110 
4111       CmdArgs.push_back(Args.MakeArgString(
4112           "-fmodule-output=" +
4113           getCXX20NamedModuleOutputPath(Args, Input.getBaseInput())));
4114     }
4115   }
4116 
4117   // Noop if we see '-fmodules-reduced-bmi' with other translation
4118   // units than module units. This is more user friendly to allow end uers to
4119   // enable this feature without asking for help from build systems.
4120   Args.ClaimAllArgs(options::OPT_modules_reduced_bmi);
4121 
4122   // We need to include the case the input file is a module file here.
4123   // Since the default compilation model for C++ module interface unit will
4124   // create temporary module file and compile the temporary module file
4125   // to get the object file. Then the `-fmodule-output` flag will be
4126   // brought to the second compilation process. So we have to claim it for
4127   // the case too.
4128   if (Input.getType() == driver::types::TY_CXXModule ||
4129       Input.getType() == driver::types::TY_PP_CXXModule ||
4130       Input.getType() == driver::types::TY_ModuleFile) {
4131     Args.ClaimAllArgs(options::OPT_fmodule_output);
4132     Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4133   }
4134 
4135   if (Args.hasArg(options::OPT_fmodules_embed_all_files))
4136     CmdArgs.push_back("-fmodules-embed-all-files");
4137 
4138   return HaveModules;
4139 }
4140 
RenderCharacterOptions(const ArgList & Args,const llvm::Triple & T,ArgStringList & CmdArgs)4141 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4142                                    ArgStringList &CmdArgs) {
4143   // -fsigned-char is default.
4144   if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4145                                      options::OPT_fno_signed_char,
4146                                      options::OPT_funsigned_char,
4147                                      options::OPT_fno_unsigned_char)) {
4148     if (A->getOption().matches(options::OPT_funsigned_char) ||
4149         A->getOption().matches(options::OPT_fno_signed_char)) {
4150       CmdArgs.push_back("-fno-signed-char");
4151     }
4152   } else if (!isSignedCharDefault(T)) {
4153     CmdArgs.push_back("-fno-signed-char");
4154   }
4155 
4156   // The default depends on the language standard.
4157   Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4158 
4159   if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4160                                      options::OPT_fno_short_wchar)) {
4161     if (A->getOption().matches(options::OPT_fshort_wchar)) {
4162       CmdArgs.push_back("-fwchar-type=short");
4163       CmdArgs.push_back("-fno-signed-wchar");
4164     } else {
4165       bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4166       CmdArgs.push_back("-fwchar-type=int");
4167       if (T.isOSzOS() ||
4168           (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4169         CmdArgs.push_back("-fno-signed-wchar");
4170       else
4171         CmdArgs.push_back("-fsigned-wchar");
4172     }
4173   } else if (T.isOSzOS())
4174     CmdArgs.push_back("-fno-signed-wchar");
4175 }
4176 
RenderObjCOptions(const ToolChain & TC,const Driver & D,const llvm::Triple & T,const ArgList & Args,ObjCRuntime & Runtime,bool InferCovariantReturns,const InputInfo & Input,ArgStringList & CmdArgs)4177 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4178                               const llvm::Triple &T, const ArgList &Args,
4179                               ObjCRuntime &Runtime, bool InferCovariantReturns,
4180                               const InputInfo &Input, ArgStringList &CmdArgs) {
4181   const llvm::Triple::ArchType Arch = TC.getArch();
4182 
4183   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4184   // is the default. Except for deployment target of 10.5, next runtime is
4185   // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4186   if (Runtime.isNonFragile()) {
4187     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4188                       options::OPT_fno_objc_legacy_dispatch,
4189                       Runtime.isLegacyDispatchDefaultForArch(Arch))) {
4190       if (TC.UseObjCMixedDispatch())
4191         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4192       else
4193         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4194     }
4195   }
4196 
4197   // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4198   // to do Array/Dictionary subscripting by default.
4199   if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4200       Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4201     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4202 
4203   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4204   // NOTE: This logic is duplicated in ToolChains.cpp.
4205   if (isObjCAutoRefCount(Args)) {
4206     TC.CheckObjCARC();
4207 
4208     CmdArgs.push_back("-fobjc-arc");
4209 
4210     // FIXME: It seems like this entire block, and several around it should be
4211     // wrapped in isObjC, but for now we just use it here as this is where it
4212     // was being used previously.
4213     if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4214       if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4215         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4216       else
4217         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4218     }
4219 
4220     // Allow the user to enable full exceptions code emission.
4221     // We default off for Objective-C, on for Objective-C++.
4222     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4223                      options::OPT_fno_objc_arc_exceptions,
4224                      /*Default=*/types::isCXX(Input.getType())))
4225       CmdArgs.push_back("-fobjc-arc-exceptions");
4226   }
4227 
4228   // Silence warning for full exception code emission options when explicitly
4229   // set to use no ARC.
4230   if (Args.hasArg(options::OPT_fno_objc_arc)) {
4231     Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4232     Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4233   }
4234 
4235   // Allow the user to control whether messages can be converted to runtime
4236   // functions.
4237   if (types::isObjC(Input.getType())) {
4238     auto *Arg = Args.getLastArg(
4239         options::OPT_fobjc_convert_messages_to_runtime_calls,
4240         options::OPT_fno_objc_convert_messages_to_runtime_calls);
4241     if (Arg &&
4242         Arg->getOption().matches(
4243             options::OPT_fno_objc_convert_messages_to_runtime_calls))
4244       CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4245   }
4246 
4247   // -fobjc-infer-related-result-type is the default, except in the Objective-C
4248   // rewriter.
4249   if (InferCovariantReturns)
4250     CmdArgs.push_back("-fno-objc-infer-related-result-type");
4251 
4252   // Pass down -fobjc-weak or -fno-objc-weak if present.
4253   if (types::isObjC(Input.getType())) {
4254     auto WeakArg =
4255         Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4256     if (!WeakArg) {
4257       // nothing to do
4258     } else if (!Runtime.allowsWeak()) {
4259       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4260         D.Diag(diag::err_objc_weak_unsupported);
4261     } else {
4262       WeakArg->render(Args, CmdArgs);
4263     }
4264   }
4265 
4266   if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4267     CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4268 }
4269 
RenderDiagnosticsOptions(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs)4270 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4271                                      ArgStringList &CmdArgs) {
4272   bool CaretDefault = true;
4273   bool ColumnDefault = true;
4274 
4275   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4276                                      options::OPT__SLASH_diagnostics_column,
4277                                      options::OPT__SLASH_diagnostics_caret)) {
4278     switch (A->getOption().getID()) {
4279     case options::OPT__SLASH_diagnostics_caret:
4280       CaretDefault = true;
4281       ColumnDefault = true;
4282       break;
4283     case options::OPT__SLASH_diagnostics_column:
4284       CaretDefault = false;
4285       ColumnDefault = true;
4286       break;
4287     case options::OPT__SLASH_diagnostics_classic:
4288       CaretDefault = false;
4289       ColumnDefault = false;
4290       break;
4291     }
4292   }
4293 
4294   // -fcaret-diagnostics is default.
4295   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4296                     options::OPT_fno_caret_diagnostics, CaretDefault))
4297     CmdArgs.push_back("-fno-caret-diagnostics");
4298 
4299   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4300                      options::OPT_fno_diagnostics_fixit_info);
4301   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4302                      options::OPT_fno_diagnostics_show_option);
4303 
4304   if (const Arg *A =
4305           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4306     CmdArgs.push_back("-fdiagnostics-show-category");
4307     CmdArgs.push_back(A->getValue());
4308   }
4309 
4310   Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4311                     options::OPT_fno_diagnostics_show_hotness);
4312 
4313   if (const Arg *A =
4314           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4315     std::string Opt =
4316         std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4317     CmdArgs.push_back(Args.MakeArgString(Opt));
4318   }
4319 
4320   if (const Arg *A =
4321           Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4322     std::string Opt =
4323         std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4324     CmdArgs.push_back(Args.MakeArgString(Opt));
4325   }
4326 
4327   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4328     CmdArgs.push_back("-fdiagnostics-format");
4329     CmdArgs.push_back(A->getValue());
4330     if (StringRef(A->getValue()) == "sarif" ||
4331         StringRef(A->getValue()) == "SARIF")
4332       D.Diag(diag::warn_drv_sarif_format_unstable);
4333   }
4334 
4335   if (const Arg *A = Args.getLastArg(
4336           options::OPT_fdiagnostics_show_note_include_stack,
4337           options::OPT_fno_diagnostics_show_note_include_stack)) {
4338     const Option &O = A->getOption();
4339     if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4340       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4341     else
4342       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4343   }
4344 
4345   handleColorDiagnosticsArgs(D, Args, CmdArgs);
4346 
4347   if (Args.hasArg(options::OPT_fansi_escape_codes))
4348     CmdArgs.push_back("-fansi-escape-codes");
4349 
4350   Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4351                      options::OPT_fno_show_source_location);
4352 
4353   Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4354                      options::OPT_fno_diagnostics_show_line_numbers);
4355 
4356   if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4357     CmdArgs.push_back("-fdiagnostics-absolute-paths");
4358 
4359   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4360                     ColumnDefault))
4361     CmdArgs.push_back("-fno-show-column");
4362 
4363   Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4364                      options::OPT_fno_spell_checking);
4365 
4366   Args.addLastArg(CmdArgs, options::OPT_warning_suppression_mappings_EQ);
4367 }
4368 
getDebugFissionKind(const Driver & D,const ArgList & Args,Arg * & Arg)4369 DwarfFissionKind tools::getDebugFissionKind(const Driver &D,
4370                                             const ArgList &Args, Arg *&Arg) {
4371   Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4372                         options::OPT_gno_split_dwarf);
4373   if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
4374     return DwarfFissionKind::None;
4375 
4376   if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
4377     return DwarfFissionKind::Split;
4378 
4379   StringRef Value = Arg->getValue();
4380   if (Value == "split")
4381     return DwarfFissionKind::Split;
4382   if (Value == "single")
4383     return DwarfFissionKind::Single;
4384 
4385   D.Diag(diag::err_drv_unsupported_option_argument)
4386       << Arg->getSpelling() << Arg->getValue();
4387   return DwarfFissionKind::None;
4388 }
4389 
renderDwarfFormat(const Driver & D,const llvm::Triple & T,const ArgList & Args,ArgStringList & CmdArgs,unsigned DwarfVersion)4390 static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4391                               const ArgList &Args, ArgStringList &CmdArgs,
4392                               unsigned DwarfVersion) {
4393   auto *DwarfFormatArg =
4394       Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4395   if (!DwarfFormatArg)
4396     return;
4397 
4398   if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4399     if (DwarfVersion < 3)
4400       D.Diag(diag::err_drv_argument_only_allowed_with)
4401           << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4402     else if (!T.isArch64Bit())
4403       D.Diag(diag::err_drv_argument_only_allowed_with)
4404           << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4405     else if (!T.isOSBinFormatELF())
4406       D.Diag(diag::err_drv_argument_only_allowed_with)
4407           << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4408   }
4409 
4410   DwarfFormatArg->render(Args, CmdArgs);
4411 }
4412 
4413 static void
renderDebugOptions(const ToolChain & TC,const Driver & D,const llvm::Triple & T,const ArgList & Args,bool IRInput,ArgStringList & CmdArgs,const InputInfo & Output,llvm::codegenoptions::DebugInfoKind & DebugInfoKind,DwarfFissionKind & DwarfFission)4414 renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4415                    const ArgList &Args, bool IRInput, ArgStringList &CmdArgs,
4416                    const InputInfo &Output,
4417                    llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4418                    DwarfFissionKind &DwarfFission) {
4419   if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
4420                    options::OPT_fno_debug_info_for_profiling, false) &&
4421       checkDebugInfoOption(
4422           Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
4423     CmdArgs.push_back("-fdebug-info-for-profiling");
4424 
4425   // The 'g' groups options involve a somewhat intricate sequence of decisions
4426   // about what to pass from the driver to the frontend, but by the time they
4427   // reach cc1 they've been factored into three well-defined orthogonal choices:
4428   //  * what level of debug info to generate
4429   //  * what dwarf version to write
4430   //  * what debugger tuning to use
4431   // This avoids having to monkey around further in cc1 other than to disable
4432   // codeview if not running in a Windows environment. Perhaps even that
4433   // decision should be made in the driver as well though.
4434   llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4435 
4436   bool SplitDWARFInlining =
4437       Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4438                    options::OPT_fno_split_dwarf_inlining, false);
4439 
4440   // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4441   // object file generation and no IR generation, -gN should not be needed. So
4442   // allow -gsplit-dwarf with either -gN or IR input.
4443   if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4444     Arg *SplitDWARFArg;
4445     DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4446     if (DwarfFission != DwarfFissionKind::None &&
4447         !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4448       DwarfFission = DwarfFissionKind::None;
4449       SplitDWARFInlining = false;
4450     }
4451   }
4452   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4453     DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4454 
4455     // If the last option explicitly specified a debug-info level, use it.
4456     if (checkDebugInfoOption(A, Args, D, TC) &&
4457         A->getOption().matches(options::OPT_gN_Group)) {
4458       DebugInfoKind = debugLevelToInfoKind(*A);
4459       // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4460       // complicated if you've disabled inline info in the skeleton CUs
4461       // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4462       // line-tables-only, so let those compose naturally in that case.
4463       if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4464           DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4465           (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4466            SplitDWARFInlining))
4467         DwarfFission = DwarfFissionKind::None;
4468     }
4469   }
4470 
4471   // If a debugger tuning argument appeared, remember it.
4472   bool HasDebuggerTuning = false;
4473   if (const Arg *A =
4474           Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4475     HasDebuggerTuning = true;
4476     if (checkDebugInfoOption(A, Args, D, TC)) {
4477       if (A->getOption().matches(options::OPT_glldb))
4478         DebuggerTuning = llvm::DebuggerKind::LLDB;
4479       else if (A->getOption().matches(options::OPT_gsce))
4480         DebuggerTuning = llvm::DebuggerKind::SCE;
4481       else if (A->getOption().matches(options::OPT_gdbx))
4482         DebuggerTuning = llvm::DebuggerKind::DBX;
4483       else
4484         DebuggerTuning = llvm::DebuggerKind::GDB;
4485     }
4486   }
4487 
4488   // If a -gdwarf argument appeared, remember it.
4489   bool EmitDwarf = false;
4490   if (const Arg *A = getDwarfNArg(Args))
4491     EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4492 
4493   bool EmitCodeView = false;
4494   if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4495     EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4496 
4497   // If the user asked for debug info but did not explicitly specify -gcodeview
4498   // or -gdwarf, ask the toolchain for the default format.
4499   if (!EmitCodeView && !EmitDwarf &&
4500       DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4501     switch (TC.getDefaultDebugFormat()) {
4502     case llvm::codegenoptions::DIF_CodeView:
4503       EmitCodeView = true;
4504       break;
4505     case llvm::codegenoptions::DIF_DWARF:
4506       EmitDwarf = true;
4507       break;
4508     }
4509   }
4510 
4511   unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4512   unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4513                                       // be lower than what the user wanted.
4514   if (EmitDwarf) {
4515     RequestedDWARFVersion = getDwarfVersion(TC, Args);
4516     // Clamp effective DWARF version to the max supported by the toolchain.
4517     EffectiveDWARFVersion =
4518         std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4519   } else {
4520     Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4521   }
4522 
4523   // -gline-directives-only supported only for the DWARF debug info.
4524   if (RequestedDWARFVersion == 0 &&
4525       DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4526     DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4527 
4528   // strict DWARF is set to false by default. But for DBX, we need it to be set
4529   // as true by default.
4530   if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4531     (void)checkDebugInfoOption(A, Args, D, TC);
4532   if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4533                    DebuggerTuning == llvm::DebuggerKind::DBX))
4534     CmdArgs.push_back("-gstrict-dwarf");
4535 
4536   // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4537   Args.ClaimAllArgs(options::OPT_g_flags_Group);
4538 
4539   // Column info is included by default for everything except SCE and
4540   // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4541   // starting columns, which, in theory, is fine for CodeView (and PDB).  In
4542   // practice, however, the Microsoft debuggers don't handle missing end columns
4543   // well, and the AIX debugger DBX also doesn't handle the columns well, so
4544   // it's better not to include any column info.
4545   if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4546     (void)checkDebugInfoOption(A, Args, D, TC);
4547   if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4548                     !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4549                         (DebuggerTuning != llvm::DebuggerKind::SCE &&
4550                          DebuggerTuning != llvm::DebuggerKind::DBX)))
4551     CmdArgs.push_back("-gno-column-info");
4552 
4553   // FIXME: Move backend command line options to the module.
4554   if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4555     // If -gline-tables-only or -gline-directives-only is the last option it
4556     // wins.
4557     if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4558                              TC)) {
4559       if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4560           DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4561         DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4562         CmdArgs.push_back("-dwarf-ext-refs");
4563         CmdArgs.push_back("-fmodule-format=obj");
4564       }
4565     }
4566   }
4567 
4568   if (T.isOSBinFormatELF() && SplitDWARFInlining)
4569     CmdArgs.push_back("-fsplit-dwarf-inlining");
4570 
4571   // After we've dealt with all combinations of things that could
4572   // make DebugInfoKind be other than None or DebugLineTablesOnly,
4573   // figure out if we need to "upgrade" it to standalone debug info.
4574   // We parse these two '-f' options whether or not they will be used,
4575   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4576   bool NeedFullDebug = Args.hasFlag(
4577       options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4578       DebuggerTuning == llvm::DebuggerKind::LLDB ||
4579           TC.GetDefaultStandaloneDebug());
4580   if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4581     (void)checkDebugInfoOption(A, Args, D, TC);
4582 
4583   if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4584       DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4585     if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4586                      options::OPT_feliminate_unused_debug_types, false))
4587       DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4588     else if (NeedFullDebug)
4589       DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4590   }
4591 
4592   if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4593                    false)) {
4594     // Source embedding is a vendor extension to DWARF v5. By now we have
4595     // checked if a DWARF version was stated explicitly, and have otherwise
4596     // fallen back to the target default, so if this is still not at least 5
4597     // we emit an error.
4598     const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4599     if (RequestedDWARFVersion < 5)
4600       D.Diag(diag::err_drv_argument_only_allowed_with)
4601           << A->getAsString(Args) << "-gdwarf-5";
4602     else if (EffectiveDWARFVersion < 5)
4603       // The toolchain has reduced allowed dwarf version, so we can't enable
4604       // -gembed-source.
4605       D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4606           << A->getAsString(Args) << TC.getTripleString() << 5
4607           << EffectiveDWARFVersion;
4608     else if (checkDebugInfoOption(A, Args, D, TC))
4609       CmdArgs.push_back("-gembed-source");
4610   }
4611 
4612   if (Args.hasFlag(options::OPT_gkey_instructions,
4613                    options::OPT_gno_key_instructions, false))
4614     CmdArgs.push_back("-gkey-instructions");
4615 
4616   if (EmitCodeView) {
4617     CmdArgs.push_back("-gcodeview");
4618 
4619     Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4620                       options::OPT_gno_codeview_ghash);
4621 
4622     Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4623                        options::OPT_gno_codeview_command_line);
4624   }
4625 
4626   Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4627                      options::OPT_gno_inline_line_tables);
4628 
4629   // When emitting remarks, we need at least debug lines in the output.
4630   if (willEmitRemarks(Args) &&
4631       DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4632     DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4633 
4634   // Adjust the debug info kind for the given toolchain.
4635   TC.adjustDebugInfoKind(DebugInfoKind, Args);
4636 
4637   // On AIX, the debugger tuning option can be omitted if it is not explicitly
4638   // set.
4639   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4640                           T.isOSAIX() && !HasDebuggerTuning
4641                               ? llvm::DebuggerKind::Default
4642                               : DebuggerTuning);
4643 
4644   // -fdebug-macro turns on macro debug info generation.
4645   if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4646                    false))
4647     if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4648                              D, TC))
4649       CmdArgs.push_back("-debug-info-macro");
4650 
4651   // -ggnu-pubnames turns on gnu style pubnames in the backend.
4652   const auto *PubnamesArg =
4653       Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4654                       options::OPT_gpubnames, options::OPT_gno_pubnames);
4655   if (DwarfFission != DwarfFissionKind::None ||
4656       (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
4657     const bool OptionSet =
4658         (PubnamesArg &&
4659          (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
4660           PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
4661     if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4662         (!PubnamesArg ||
4663          (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4664           !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
4665       CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4666                                            options::OPT_gpubnames)
4667                             ? "-gpubnames"
4668                             : "-ggnu-pubnames");
4669   }
4670   const auto *SimpleTemplateNamesArg =
4671       Args.getLastArg(options::OPT_gsimple_template_names,
4672                       options::OPT_gno_simple_template_names);
4673   bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4674   if (SimpleTemplateNamesArg &&
4675       checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4676     const auto &Opt = SimpleTemplateNamesArg->getOption();
4677     if (Opt.matches(options::OPT_gsimple_template_names)) {
4678       ForwardTemplateParams = true;
4679       CmdArgs.push_back("-gsimple-template-names=simple");
4680     }
4681   }
4682 
4683   // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4684   bool UseDebugTemplateAlias =
4685       DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4686   if (const auto *DebugTemplateAlias = Args.getLastArg(
4687           options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
4688     // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4689     // asks for it we should let them have it (if the target supports it).
4690     if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
4691       const auto &Opt = DebugTemplateAlias->getOption();
4692       UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
4693     }
4694   }
4695   if (UseDebugTemplateAlias)
4696     CmdArgs.push_back("-gtemplate-alias");
4697 
4698   if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4699     StringRef v = A->getValue();
4700     CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4701   }
4702 
4703   Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4704                     options::OPT_fno_debug_ranges_base_address);
4705 
4706   // -gdwarf-aranges turns on the emission of the aranges section in the
4707   // backend.
4708   if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);
4709       A && checkDebugInfoOption(A, Args, D, TC)) {
4710     CmdArgs.push_back("-mllvm");
4711     CmdArgs.push_back("-generate-arange-section");
4712   }
4713 
4714   Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4715                     options::OPT_fno_force_dwarf_frame);
4716 
4717   bool EnableTypeUnits = false;
4718   if (Args.hasFlag(options::OPT_fdebug_types_section,
4719                    options::OPT_fno_debug_types_section, false)) {
4720     if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4721       D.Diag(diag::err_drv_unsupported_opt_for_target)
4722           << Args.getLastArg(options::OPT_fdebug_types_section)
4723                  ->getAsString(Args)
4724           << T.getTriple();
4725     } else if (checkDebugInfoOption(
4726                    Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4727                    TC)) {
4728       EnableTypeUnits = true;
4729       CmdArgs.push_back("-mllvm");
4730       CmdArgs.push_back("-generate-type-units");
4731     }
4732   }
4733 
4734   if (const Arg *A =
4735           Args.getLastArg(options::OPT_gomit_unreferenced_methods,
4736                           options::OPT_gno_omit_unreferenced_methods))
4737     (void)checkDebugInfoOption(A, Args, D, TC);
4738   if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
4739                    options::OPT_gno_omit_unreferenced_methods, false) &&
4740       (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
4741        DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
4742       !EnableTypeUnits) {
4743     CmdArgs.push_back("-gomit-unreferenced-methods");
4744   }
4745 
4746   // To avoid join/split of directory+filename, the integrated assembler prefers
4747   // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4748   // form before DWARF v5.
4749   if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4750                     options::OPT_fno_dwarf_directory_asm,
4751                     TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4752     CmdArgs.push_back("-fno-dwarf-directory-asm");
4753 
4754   // Decide how to render forward declarations of template instantiations.
4755   // SCE wants full descriptions, others just get them in the name.
4756   if (ForwardTemplateParams)
4757     CmdArgs.push_back("-debug-forward-template-params");
4758 
4759   // Do we need to explicitly import anonymous namespaces into the parent
4760   // scope?
4761   if (DebuggerTuning == llvm::DebuggerKind::SCE)
4762     CmdArgs.push_back("-dwarf-explicit-import");
4763 
4764   renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4765   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4766 
4767   // This controls whether or not we perform JustMyCode instrumentation.
4768   if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
4769     if (TC.getTriple().isOSBinFormatELF() ||
4770         TC.getTriple().isWindowsMSVCEnvironment()) {
4771       if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
4772         CmdArgs.push_back("-fjmc");
4773       else if (D.IsCLMode())
4774         D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
4775                                                              << "'/Zi', '/Z7'";
4776       else
4777         D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
4778                                                              << "-g";
4779     } else {
4780       D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
4781     }
4782   }
4783 
4784   // Add in -fdebug-compilation-dir if necessary.
4785   const char *DebugCompilationDir =
4786       addDebugCompDirArg(Args, CmdArgs, D.getVFS());
4787 
4788   addDebugPrefixMapArg(D, TC, Args, CmdArgs);
4789 
4790   // Add the output path to the object file for CodeView debug infos.
4791   if (EmitCodeView && Output.isFilename())
4792     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
4793                        Output.getFilename());
4794 }
4795 
ProcessVSRuntimeLibrary(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)4796 static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
4797                                     ArgStringList &CmdArgs) {
4798   unsigned RTOptionID = options::OPT__SLASH_MT;
4799 
4800   if (Args.hasArg(options::OPT__SLASH_LDd))
4801     // The /LDd option implies /MTd. The dependent lib part can be overridden,
4802     // but defining _DEBUG is sticky.
4803     RTOptionID = options::OPT__SLASH_MTd;
4804 
4805   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4806     RTOptionID = A->getOption().getID();
4807 
4808   if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4809     RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4810                      .Case("static", options::OPT__SLASH_MT)
4811                      .Case("static_dbg", options::OPT__SLASH_MTd)
4812                      .Case("dll", options::OPT__SLASH_MD)
4813                      .Case("dll_dbg", options::OPT__SLASH_MDd)
4814                      .Default(options::OPT__SLASH_MT);
4815   }
4816 
4817   StringRef FlagForCRT;
4818   switch (RTOptionID) {
4819   case options::OPT__SLASH_MD:
4820     if (Args.hasArg(options::OPT__SLASH_LDd))
4821       CmdArgs.push_back("-D_DEBUG");
4822     CmdArgs.push_back("-D_MT");
4823     CmdArgs.push_back("-D_DLL");
4824     FlagForCRT = "--dependent-lib=msvcrt";
4825     break;
4826   case options::OPT__SLASH_MDd:
4827     CmdArgs.push_back("-D_DEBUG");
4828     CmdArgs.push_back("-D_MT");
4829     CmdArgs.push_back("-D_DLL");
4830     FlagForCRT = "--dependent-lib=msvcrtd";
4831     break;
4832   case options::OPT__SLASH_MT:
4833     if (Args.hasArg(options::OPT__SLASH_LDd))
4834       CmdArgs.push_back("-D_DEBUG");
4835     CmdArgs.push_back("-D_MT");
4836     CmdArgs.push_back("-flto-visibility-public-std");
4837     FlagForCRT = "--dependent-lib=libcmt";
4838     break;
4839   case options::OPT__SLASH_MTd:
4840     CmdArgs.push_back("-D_DEBUG");
4841     CmdArgs.push_back("-D_MT");
4842     CmdArgs.push_back("-flto-visibility-public-std");
4843     FlagForCRT = "--dependent-lib=libcmtd";
4844     break;
4845   default:
4846     llvm_unreachable("Unexpected option ID.");
4847   }
4848 
4849   if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4850     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4851   } else {
4852     CmdArgs.push_back(FlagForCRT.data());
4853 
4854     // This provides POSIX compatibility (maps 'open' to '_open'), which most
4855     // users want.  The /Za flag to cl.exe turns this off, but it's not
4856     // implemented in clang.
4857     CmdArgs.push_back("--dependent-lib=oldnames");
4858   }
4859 
4860   // All Arm64EC object files implicitly add softintrin.lib. This is necessary
4861   // even if the file doesn't actually refer to any of the routines because
4862   // the CRT itself has incomplete dependency markings.
4863   if (TC.getTriple().isWindowsArm64EC())
4864     CmdArgs.push_back("--dependent-lib=softintrin");
4865 }
4866 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const4867 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4868                          const InputInfo &Output, const InputInfoList &Inputs,
4869                          const ArgList &Args, const char *LinkingOutput) const {
4870   const auto &TC = getToolChain();
4871   const llvm::Triple &RawTriple = TC.getTriple();
4872   const llvm::Triple &Triple = TC.getEffectiveTriple();
4873   const std::string &TripleStr = Triple.getTriple();
4874 
4875   bool KernelOrKext =
4876       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4877   const Driver &D = TC.getDriver();
4878   ArgStringList CmdArgs;
4879 
4880   assert(Inputs.size() >= 1 && "Must have at least one input.");
4881   // CUDA/HIP compilation may have multiple inputs (source file + results of
4882   // device-side compilations). OpenMP device jobs also take the host IR as a
4883   // second input. Module precompilation accepts a list of header files to
4884   // include as part of the module. API extraction accepts a list of header
4885   // files whose API information is emitted in the output. All other jobs are
4886   // expected to have exactly one input. SYCL compilation only expects a
4887   // single input.
4888   bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4889   bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
4890   bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4891   bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
4892   bool IsSYCL = JA.isOffloading(Action::OFK_SYCL);
4893   bool IsSYCLDevice = JA.isDeviceOffloading(Action::OFK_SYCL);
4894   bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
4895   bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
4896   bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4897                                  JA.isDeviceOffloading(Action::OFK_Host));
4898   bool IsHostOffloadingAction =
4899       JA.isHostOffloading(Action::OFK_OpenMP) ||
4900       JA.isHostOffloading(Action::OFK_SYCL) ||
4901       (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
4902        Args.hasFlag(options::OPT_offload_new_driver,
4903                     options::OPT_no_offload_new_driver,
4904                     C.isOffloadingHostKind(Action::OFK_Cuda)));
4905 
4906   bool IsRDCMode =
4907       Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4908 
4909   auto LTOMode = IsDeviceOffloadAction ? D.getOffloadLTOMode() : D.getLTOMode();
4910   bool IsUsingLTO = LTOMode != LTOK_None;
4911 
4912   // Extract API doesn't have a main input file, so invent a fake one as a
4913   // placeholder.
4914   InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4915                                        "extract-api");
4916 
4917   const InputInfo &Input =
4918       IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4919 
4920   InputInfoList ExtractAPIInputs;
4921   InputInfoList HostOffloadingInputs;
4922   const InputInfo *CudaDeviceInput = nullptr;
4923   const InputInfo *OpenMPDeviceInput = nullptr;
4924   for (const InputInfo &I : Inputs) {
4925     if (&I == &Input || I.getType() == types::TY_Nothing) {
4926       // This is the primary input or contains nothing.
4927     } else if (IsExtractAPI) {
4928       auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4929       if (I.getType() != ExpectedInputType) {
4930         D.Diag(diag::err_drv_extract_api_wrong_kind)
4931             << I.getFilename() << types::getTypeName(I.getType())
4932             << types::getTypeName(ExpectedInputType);
4933       }
4934       ExtractAPIInputs.push_back(I);
4935     } else if (IsHostOffloadingAction) {
4936       HostOffloadingInputs.push_back(I);
4937     } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4938       CudaDeviceInput = &I;
4939     } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4940       OpenMPDeviceInput = &I;
4941     } else {
4942       llvm_unreachable("unexpectedly given multiple inputs");
4943     }
4944   }
4945 
4946   const llvm::Triple *AuxTriple =
4947       (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4948   bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4949   bool IsUEFI = RawTriple.isUEFI();
4950   bool IsIAMCU = RawTriple.isOSIAMCU();
4951 
4952   // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations.  Even when compiling in
4953   // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4954   // Windows), we need to pass Windows-specific flags to cc1.
4955   if (IsCuda || IsHIP || IsSYCL)
4956     IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4957 
4958   // C++ is not supported for IAMCU.
4959   if (IsIAMCU && types::isCXX(Input.getType()))
4960     D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4961 
4962   // Invoke ourselves in -cc1 mode.
4963   //
4964   // FIXME: Implement custom jobs for internal actions.
4965   CmdArgs.push_back("-cc1");
4966 
4967   // Add the "effective" target triple.
4968   CmdArgs.push_back("-triple");
4969   CmdArgs.push_back(Args.MakeArgString(TripleStr));
4970 
4971   if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4972     DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4973     Args.ClaimAllArgs(options::OPT_MJ);
4974   } else if (const Arg *GenCDBFragment =
4975                  Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4976     DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4977                                          TripleStr, Output, Input, Args);
4978     Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4979   }
4980 
4981   if (IsCuda || IsHIP) {
4982     // We have to pass the triple of the host if compiling for a CUDA/HIP device
4983     // and vice-versa.
4984     std::string NormalizedTriple;
4985     if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
4986         JA.isDeviceOffloading(Action::OFK_HIP))
4987       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4988                              ->getTriple()
4989                              .normalize();
4990     else {
4991       // Host-side compilation.
4992       NormalizedTriple =
4993           (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4994                   : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4995               ->getTriple()
4996               .normalize();
4997       if (IsCuda) {
4998         // We need to figure out which CUDA version we're compiling for, as that
4999         // determines how we load and launch GPU kernels.
5000         auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5001             C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5002         assert(CTC && "Expected valid CUDA Toolchain.");
5003         if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5004           CmdArgs.push_back(Args.MakeArgString(
5005               Twine("-target-sdk-version=") +
5006               CudaVersionToString(CTC->CudaInstallation.version())));
5007         // Unsized function arguments used for variadics were introduced in
5008         // CUDA-9.0. We still do not support generating code that actually uses
5009         // variadic arguments yet, but we do need to allow parsing them as
5010         // recent CUDA headers rely on that.
5011         // https://github.com/llvm/llvm-project/issues/58410
5012         if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
5013           CmdArgs.push_back("-fcuda-allow-variadic-functions");
5014       }
5015     }
5016     CmdArgs.push_back("-aux-triple");
5017     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
5018 
5019     if (JA.isDeviceOffloading(Action::OFK_HIP) &&
5020         (getToolChain().getTriple().isAMDGPU() ||
5021          (getToolChain().getTriple().isSPIRV() &&
5022           getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5023       // Device side compilation printf
5024       if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
5025         CmdArgs.push_back(Args.MakeArgString(
5026             "-mprintf-kind=" +
5027             Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
5028         // Force compiler error on invalid conversion specifiers
5029         CmdArgs.push_back(
5030             Args.MakeArgString("-Werror=format-invalid-specifier"));
5031       }
5032     }
5033   }
5034 
5035   // Optimization level for CodeGen.
5036   if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5037     if (A->getOption().matches(options::OPT_O4)) {
5038       CmdArgs.push_back("-O3");
5039       D.Diag(diag::warn_O4_is_O3);
5040     } else {
5041       A->render(Args, CmdArgs);
5042     }
5043   }
5044 
5045   // Unconditionally claim the printf option now to avoid unused diagnostic.
5046   if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
5047     PF->claim();
5048 
5049   if (IsSYCL) {
5050     if (IsSYCLDevice) {
5051       // Host triple is needed when doing SYCL device compilations.
5052       llvm::Triple AuxT = C.getDefaultToolChain().getTriple();
5053       std::string NormalizedTriple = AuxT.normalize();
5054       CmdArgs.push_back("-aux-triple");
5055       CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
5056 
5057       // We want to compile sycl kernels.
5058       CmdArgs.push_back("-fsycl-is-device");
5059 
5060       // Set O2 optimization level by default
5061       if (!Args.getLastArg(options::OPT_O_Group))
5062         CmdArgs.push_back("-O2");
5063     } else {
5064       // Add any options that are needed specific to SYCL offload while
5065       // performing the host side compilation.
5066 
5067       // Let the front-end host compilation flow know about SYCL offload
5068       // compilation.
5069       CmdArgs.push_back("-fsycl-is-host");
5070     }
5071 
5072     // Set options for both host and device.
5073     Arg *SYCLStdArg = Args.getLastArg(options::OPT_sycl_std_EQ);
5074     if (SYCLStdArg) {
5075       SYCLStdArg->render(Args, CmdArgs);
5076     } else {
5077       // Ensure the default version in SYCL mode is 2020.
5078       CmdArgs.push_back("-sycl-std=2020");
5079     }
5080   }
5081 
5082   if (Args.hasArg(options::OPT_fclangir))
5083     CmdArgs.push_back("-fclangir");
5084 
5085   if (IsOpenMPDevice) {
5086     // We have to pass the triple of the host if compiling for an OpenMP device.
5087     std::string NormalizedTriple =
5088         C.getSingleOffloadToolChain<Action::OFK_Host>()
5089             ->getTriple()
5090             .normalize();
5091     CmdArgs.push_back("-aux-triple");
5092     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
5093   }
5094 
5095   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5096                                Triple.getArch() == llvm::Triple::thumb)) {
5097     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5098     unsigned Version = 0;
5099     bool Failure =
5100         Triple.getArchName().substr(Offset).consumeInteger(10, Version);
5101     if (Failure || Version < 7)
5102       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5103                                                 << TripleStr;
5104   }
5105 
5106   // Push all default warning arguments that are specific to
5107   // the given target.  These come before user provided warning options
5108   // are provided.
5109   TC.addClangWarningOptions(CmdArgs);
5110 
5111   // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5112   if (Triple.isSPIR() || Triple.isSPIRV())
5113     CmdArgs.push_back("-Wspir-compat");
5114 
5115   // Select the appropriate action.
5116   RewriteKind rewriteKind = RK_None;
5117 
5118   bool UnifiedLTO = false;
5119   if (IsUsingLTO) {
5120     UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5121                               options::OPT_fno_unified_lto, Triple.isPS());
5122     if (UnifiedLTO)
5123       CmdArgs.push_back("-funified-lto");
5124   }
5125 
5126   // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5127   // it claims when not running an assembler. Otherwise, clang would emit
5128   // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5129   // flags while debugging something. That'd be somewhat inconvenient, and it's
5130   // also inconsistent with most other flags -- we don't warn on
5131   // -ffunction-sections not being used in -E mode either for example, even
5132   // though it's not really used either.
5133   if (!isa<AssembleJobAction>(JA)) {
5134     // The args claimed here should match the args used in
5135     // CollectArgsForIntegratedAssembler().
5136     if (TC.useIntegratedAs()) {
5137       Args.ClaimAllArgs(options::OPT_mrelax_all);
5138       Args.ClaimAllArgs(options::OPT_mno_relax_all);
5139       Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5140       Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5141       switch (C.getDefaultToolChain().getArch()) {
5142       case llvm::Triple::arm:
5143       case llvm::Triple::armeb:
5144       case llvm::Triple::thumb:
5145       case llvm::Triple::thumbeb:
5146         Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5147         break;
5148       default:
5149         break;
5150       }
5151     }
5152     Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5153     Args.ClaimAllArgs(options::OPT_Xassembler);
5154     Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5155   }
5156 
5157   if (isa<AnalyzeJobAction>(JA)) {
5158     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5159     CmdArgs.push_back("-analyze");
5160   } else if (isa<PreprocessJobAction>(JA)) {
5161     if (Output.getType() == types::TY_Dependencies)
5162       CmdArgs.push_back("-Eonly");
5163     else {
5164       CmdArgs.push_back("-E");
5165       if (Args.hasArg(options::OPT_rewrite_objc) &&
5166           !Args.hasArg(options::OPT_g_Group))
5167         CmdArgs.push_back("-P");
5168       else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5169         CmdArgs.push_back("-fdirectives-only");
5170     }
5171   } else if (isa<AssembleJobAction>(JA)) {
5172     CmdArgs.push_back("-emit-obj");
5173 
5174     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5175 
5176     // Also ignore explicit -force_cpusubtype_ALL option.
5177     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5178   } else if (isa<PrecompileJobAction>(JA)) {
5179     if (JA.getType() == types::TY_Nothing)
5180       CmdArgs.push_back("-fsyntax-only");
5181     else if (JA.getType() == types::TY_ModuleFile)
5182       CmdArgs.push_back("-emit-module-interface");
5183     else if (JA.getType() == types::TY_HeaderUnit)
5184       CmdArgs.push_back("-emit-header-unit");
5185     else if (!Args.hasArg(options::OPT_ignore_pch))
5186       CmdArgs.push_back("-emit-pch");
5187   } else if (isa<VerifyPCHJobAction>(JA)) {
5188     CmdArgs.push_back("-verify-pch");
5189   } else if (isa<ExtractAPIJobAction>(JA)) {
5190     assert(JA.getType() == types::TY_API_INFO &&
5191            "Extract API actions must generate a API information.");
5192     CmdArgs.push_back("-extract-api");
5193 
5194     if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5195       PrettySGFArg->render(Args, CmdArgs);
5196 
5197     Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5198 
5199     if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5200       ProductNameArg->render(Args, CmdArgs);
5201     if (Arg *ExtractAPIIgnoresFileArg =
5202             Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5203       ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
5204     if (Arg *EmitExtensionSymbolGraphs =
5205             Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5206       if (!SymbolGraphDirArg)
5207         D.Diag(diag::err_drv_missing_symbol_graph_dir);
5208 
5209       EmitExtensionSymbolGraphs->render(Args, CmdArgs);
5210     }
5211     if (SymbolGraphDirArg)
5212       SymbolGraphDirArg->render(Args, CmdArgs);
5213   } else {
5214     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5215            "Invalid action for clang tool.");
5216     if (JA.getType() == types::TY_Nothing) {
5217       CmdArgs.push_back("-fsyntax-only");
5218     } else if (JA.getType() == types::TY_LLVM_IR ||
5219                JA.getType() == types::TY_LTO_IR) {
5220       CmdArgs.push_back("-emit-llvm");
5221     } else if (JA.getType() == types::TY_LLVM_BC ||
5222                JA.getType() == types::TY_LTO_BC) {
5223       // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5224       if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5225           Args.hasArg(options::OPT_emit_llvm)) {
5226         CmdArgs.push_back("-emit-llvm");
5227       } else {
5228         CmdArgs.push_back("-emit-llvm-bc");
5229       }
5230     } else if (JA.getType() == types::TY_IFS ||
5231                JA.getType() == types::TY_IFS_CPP) {
5232       StringRef ArgStr =
5233           Args.hasArg(options::OPT_interface_stub_version_EQ)
5234               ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5235               : "ifs-v1";
5236       CmdArgs.push_back("-emit-interface-stubs");
5237       CmdArgs.push_back(
5238           Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
5239     } else if (JA.getType() == types::TY_PP_Asm) {
5240       CmdArgs.push_back("-S");
5241     } else if (JA.getType() == types::TY_AST) {
5242       if (!Args.hasArg(options::OPT_ignore_pch))
5243         CmdArgs.push_back("-emit-pch");
5244     } else if (JA.getType() == types::TY_ModuleFile) {
5245       CmdArgs.push_back("-module-file-info");
5246     } else if (JA.getType() == types::TY_RewrittenObjC) {
5247       CmdArgs.push_back("-rewrite-objc");
5248       rewriteKind = RK_NonFragile;
5249     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5250       CmdArgs.push_back("-rewrite-objc");
5251       rewriteKind = RK_Fragile;
5252     } else if (JA.getType() == types::TY_CIR) {
5253       CmdArgs.push_back("-emit-cir");
5254     } else {
5255       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5256     }
5257 
5258     // Preserve use-list order by default when emitting bitcode, so that
5259     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5260     // same result as running passes here.  For LTO, we don't need to preserve
5261     // the use-list order, since serialization to bitcode is part of the flow.
5262     if (JA.getType() == types::TY_LLVM_BC)
5263       CmdArgs.push_back("-emit-llvm-uselists");
5264 
5265     if (IsUsingLTO) {
5266       if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
5267           !Args.hasFlag(options::OPT_offload_new_driver,
5268                         options::OPT_no_offload_new_driver,
5269                         C.isOffloadingHostKind(Action::OFK_Cuda)) &&
5270           !Triple.isAMDGPU()) {
5271         D.Diag(diag::err_drv_unsupported_opt_for_target)
5272             << Args.getLastArg(options::OPT_foffload_lto,
5273                                options::OPT_foffload_lto_EQ)
5274                    ->getAsString(Args)
5275             << Triple.getTriple();
5276       } else if (Triple.isNVPTX() && !IsRDCMode &&
5277                  JA.isDeviceOffloading(Action::OFK_Cuda)) {
5278         D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5279             << Args.getLastArg(options::OPT_foffload_lto,
5280                                options::OPT_foffload_lto_EQ)
5281                    ->getAsString(Args)
5282             << "-fno-gpu-rdc";
5283       } else {
5284         assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5285         CmdArgs.push_back(Args.MakeArgString(
5286             Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5287         // PS4 uses the legacy LTO API, which does not support some of the
5288         // features enabled by -flto-unit.
5289         if (!RawTriple.isPS4() ||
5290             (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
5291           CmdArgs.push_back("-flto-unit");
5292       }
5293     }
5294   }
5295 
5296   Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5297 
5298   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5299     if (!types::isLLVMIR(Input.getType()))
5300       D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5301     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5302   }
5303 
5304   if (Triple.isPPC())
5305     Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5306                       options::OPT_mno_regnames);
5307 
5308   if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5309     Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5310 
5311   if (Args.getLastArg(options::OPT_save_temps_EQ))
5312     Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5313 
5314   auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5315                                      options::OPT_fmemory_profile_EQ,
5316                                      options::OPT_fno_memory_profile);
5317   if (MemProfArg &&
5318       !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5319     MemProfArg->render(Args, CmdArgs);
5320 
5321   if (auto *MemProfUseArg =
5322           Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5323     if (MemProfArg)
5324       D.Diag(diag::err_drv_argument_not_allowed_with)
5325           << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5326     if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5327                                             options::OPT_fprofile_generate_EQ))
5328       D.Diag(diag::err_drv_argument_not_allowed_with)
5329           << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5330     MemProfUseArg->render(Args, CmdArgs);
5331   }
5332 
5333   // Embed-bitcode option.
5334   // Only white-listed flags below are allowed to be embedded.
5335   if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5336       (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
5337     // Add flags implied by -fembed-bitcode.
5338     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5339     // Disable all llvm IR level optimizations.
5340     CmdArgs.push_back("-disable-llvm-passes");
5341 
5342     // Render target options.
5343     TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5344 
5345     // reject options that shouldn't be supported in bitcode
5346     // also reject kernel/kext
5347     static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5348         options::OPT_mkernel,
5349         options::OPT_fapple_kext,
5350         options::OPT_ffunction_sections,
5351         options::OPT_fno_function_sections,
5352         options::OPT_fdata_sections,
5353         options::OPT_fno_data_sections,
5354         options::OPT_fbasic_block_sections_EQ,
5355         options::OPT_funique_internal_linkage_names,
5356         options::OPT_fno_unique_internal_linkage_names,
5357         options::OPT_funique_section_names,
5358         options::OPT_fno_unique_section_names,
5359         options::OPT_funique_basic_block_section_names,
5360         options::OPT_fno_unique_basic_block_section_names,
5361         options::OPT_mrestrict_it,
5362         options::OPT_mno_restrict_it,
5363         options::OPT_mstackrealign,
5364         options::OPT_mno_stackrealign,
5365         options::OPT_mstack_alignment,
5366         options::OPT_mcmodel_EQ,
5367         options::OPT_mlong_calls,
5368         options::OPT_mno_long_calls,
5369         options::OPT_ggnu_pubnames,
5370         options::OPT_gdwarf_aranges,
5371         options::OPT_fdebug_types_section,
5372         options::OPT_fno_debug_types_section,
5373         options::OPT_fdwarf_directory_asm,
5374         options::OPT_fno_dwarf_directory_asm,
5375         options::OPT_mrelax_all,
5376         options::OPT_mno_relax_all,
5377         options::OPT_ftrap_function_EQ,
5378         options::OPT_ffixed_r9,
5379         options::OPT_mfix_cortex_a53_835769,
5380         options::OPT_mno_fix_cortex_a53_835769,
5381         options::OPT_ffixed_x18,
5382         options::OPT_mglobal_merge,
5383         options::OPT_mno_global_merge,
5384         options::OPT_mred_zone,
5385         options::OPT_mno_red_zone,
5386         options::OPT_Wa_COMMA,
5387         options::OPT_Xassembler,
5388         options::OPT_mllvm,
5389         options::OPT_mmlir,
5390     };
5391     for (const auto &A : Args)
5392       if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5393         D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5394 
5395     // Render the CodeGen options that need to be passed.
5396     Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5397                        options::OPT_fno_optimize_sibling_calls);
5398 
5399     RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
5400                                CmdArgs, JA);
5401 
5402     // Render ABI arguments
5403     switch (TC.getArch()) {
5404     default: break;
5405     case llvm::Triple::arm:
5406     case llvm::Triple::armeb:
5407     case llvm::Triple::thumbeb:
5408       RenderARMABI(D, Triple, Args, CmdArgs);
5409       break;
5410     case llvm::Triple::aarch64:
5411     case llvm::Triple::aarch64_32:
5412     case llvm::Triple::aarch64_be:
5413       RenderAArch64ABI(Triple, Args, CmdArgs);
5414       break;
5415     }
5416 
5417     // Input/Output file.
5418     if (Output.getType() == types::TY_Dependencies) {
5419       // Handled with other dependency code.
5420     } else if (Output.isFilename()) {
5421       CmdArgs.push_back("-o");
5422       CmdArgs.push_back(Output.getFilename());
5423     } else {
5424       assert(Output.isNothing() && "Input output.");
5425     }
5426 
5427     for (const auto &II : Inputs) {
5428       addDashXForInput(Args, II, CmdArgs);
5429       if (II.isFilename())
5430         CmdArgs.push_back(II.getFilename());
5431       else
5432         II.getInputArg().renderAsInput(Args, CmdArgs);
5433     }
5434 
5435     C.addCommand(std::make_unique<Command>(
5436         JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
5437         CmdArgs, Inputs, Output, D.getPrependArg()));
5438     return;
5439   }
5440 
5441   if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5442     CmdArgs.push_back("-fembed-bitcode=marker");
5443 
5444   // We normally speed up the clang process a bit by skipping destructors at
5445   // exit, but when we're generating diagnostics we can rely on some of the
5446   // cleanup.
5447   if (!C.isForDiagnostics())
5448     CmdArgs.push_back("-disable-free");
5449   CmdArgs.push_back("-clear-ast-before-backend");
5450 
5451 #ifdef NDEBUG
5452   const bool IsAssertBuild = false;
5453 #else
5454   const bool IsAssertBuild = true;
5455 #endif
5456 
5457   // Disable the verification pass in asserts builds unless otherwise specified.
5458   if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5459                    options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5460     CmdArgs.push_back("-disable-llvm-verifier");
5461   }
5462 
5463   // Discard value names in assert builds unless otherwise specified.
5464   if (Args.hasFlag(options::OPT_fdiscard_value_names,
5465                    options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5466     if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5467         llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5468           return types::isLLVMIR(II.getType());
5469         })) {
5470       D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5471     }
5472     CmdArgs.push_back("-discard-value-names");
5473   }
5474 
5475   // Set the main file name, so that debug info works even with
5476   // -save-temps.
5477   CmdArgs.push_back("-main-file-name");
5478   CmdArgs.push_back(getBaseInputName(Args, Input));
5479 
5480   // Some flags which affect the language (via preprocessor
5481   // defines).
5482   if (Args.hasArg(options::OPT_static))
5483     CmdArgs.push_back("-static-define");
5484 
5485   Args.AddLastArg(CmdArgs, options::OPT_static_libclosure);
5486 
5487   if (Args.hasArg(options::OPT_municode))
5488     CmdArgs.push_back("-DUNICODE");
5489 
5490   if (isa<AnalyzeJobAction>(JA))
5491     RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5492 
5493   if (isa<AnalyzeJobAction>(JA) ||
5494       (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5495     CmdArgs.push_back("-setup-static-analyzer");
5496 
5497   // Enable compatilibily mode to avoid analyzer-config related errors.
5498   // Since we can't access frontend flags through hasArg, let's manually iterate
5499   // through them.
5500   bool FoundAnalyzerConfig = false;
5501   for (auto *Arg : Args.filtered(options::OPT_Xclang))
5502     if (StringRef(Arg->getValue()) == "-analyzer-config") {
5503       FoundAnalyzerConfig = true;
5504       break;
5505     }
5506   if (!FoundAnalyzerConfig)
5507     for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5508       if (StringRef(Arg->getValue()) == "-analyzer-config") {
5509         FoundAnalyzerConfig = true;
5510         break;
5511       }
5512   if (FoundAnalyzerConfig)
5513     CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5514 
5515   CheckCodeGenerationOptions(D, Args);
5516 
5517   unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5518   assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5519   if (FunctionAlignment) {
5520     CmdArgs.push_back("-function-alignment");
5521     CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
5522   }
5523 
5524   // We support -falign-loops=N where N is a power of 2. GCC supports more
5525   // forms.
5526   if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5527     unsigned Value = 0;
5528     if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5529       TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5530           << A->getAsString(Args) << A->getValue();
5531     else if (Value & (Value - 1))
5532       TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5533           << A->getAsString(Args) << A->getValue();
5534     // Treat =0 as unspecified (use the target preference).
5535     if (Value)
5536       CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5537                                            Twine(std::min(Value, 65536u))));
5538   }
5539 
5540   if (Triple.isOSzOS()) {
5541     // On z/OS some of the system header feature macros need to
5542     // be defined to enable most cross platform projects to build
5543     // successfully.  Ths include the libc++ library.  A
5544     // complicating factor is that users can define these
5545     // macros to the same or different values.  We need to add
5546     // the definition for these macros to the compilation command
5547     // if the user hasn't already defined them.
5548 
5549     auto findMacroDefinition = [&](const std::string &Macro) {
5550       auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5551       return llvm::any_of(MacroDefs, [&](const std::string &M) {
5552         return M == Macro || M.find(Macro + '=') != std::string::npos;
5553       });
5554     };
5555 
5556     // _UNIX03_WITHDRAWN is required for libcxx & porting.
5557     if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5558       CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5559     // _OPEN_DEFAULT is required for XL compat
5560     if (!findMacroDefinition("_OPEN_DEFAULT"))
5561       CmdArgs.push_back("-D_OPEN_DEFAULT");
5562     if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5563       // _XOPEN_SOURCE=600 is required for libcxx.
5564       if (!findMacroDefinition("_XOPEN_SOURCE"))
5565         CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5566     }
5567   }
5568 
5569   llvm::Reloc::Model RelocationModel;
5570   unsigned PICLevel;
5571   bool IsPIE;
5572   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5573   Arg *LastPICDataRelArg =
5574       Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5575                       options::OPT_mpic_data_is_text_relative);
5576   bool NoPICDataIsTextRelative = false;
5577   if (LastPICDataRelArg) {
5578     if (LastPICDataRelArg->getOption().matches(
5579             options::OPT_mno_pic_data_is_text_relative)) {
5580       NoPICDataIsTextRelative = true;
5581       if (!PICLevel)
5582         D.Diag(diag::err_drv_argument_only_allowed_with)
5583             << "-mno-pic-data-is-text-relative"
5584             << "-fpic/-fpie";
5585     }
5586     if (!Triple.isSystemZ())
5587       D.Diag(diag::err_drv_unsupported_opt_for_target)
5588           << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5589                                       : "-mpic-data-is-text-relative")
5590           << RawTriple.str();
5591   }
5592 
5593   bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5594                 RelocationModel == llvm::Reloc::ROPI_RWPI;
5595   bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5596                 RelocationModel == llvm::Reloc::ROPI_RWPI;
5597 
5598   if (Args.hasArg(options::OPT_mcmse) &&
5599       !Args.hasArg(options::OPT_fallow_unsupported)) {
5600     if (IsROPI)
5601       D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5602     if (IsRWPI)
5603       D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5604   }
5605 
5606   if (IsROPI && types::isCXX(Input.getType()) &&
5607       !Args.hasArg(options::OPT_fallow_unsupported))
5608     D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5609 
5610   const char *RMName = RelocationModelName(RelocationModel);
5611   if (RMName) {
5612     CmdArgs.push_back("-mrelocation-model");
5613     CmdArgs.push_back(RMName);
5614   }
5615   if (PICLevel > 0) {
5616     CmdArgs.push_back("-pic-level");
5617     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5618     if (IsPIE)
5619       CmdArgs.push_back("-pic-is-pie");
5620     if (NoPICDataIsTextRelative)
5621       CmdArgs.push_back("-mcmodel=medium");
5622   }
5623 
5624   if (RelocationModel == llvm::Reloc::ROPI ||
5625       RelocationModel == llvm::Reloc::ROPI_RWPI)
5626     CmdArgs.push_back("-fropi");
5627   if (RelocationModel == llvm::Reloc::RWPI ||
5628       RelocationModel == llvm::Reloc::ROPI_RWPI)
5629     CmdArgs.push_back("-frwpi");
5630 
5631   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5632     CmdArgs.push_back("-meabi");
5633     CmdArgs.push_back(A->getValue());
5634   }
5635 
5636   // -fsemantic-interposition is forwarded to CC1: set the
5637   // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5638   // make default visibility external linkage definitions dso_preemptable.
5639   //
5640   // -fno-semantic-interposition: if the target supports .Lfoo$local local
5641   // aliases (make default visibility external linkage definitions dso_local).
5642   // This is the CC1 default for ELF to match COFF/Mach-O.
5643   //
5644   // Otherwise use Clang's traditional behavior: like
5645   // -fno-semantic-interposition but local aliases are not used. So references
5646   // can be interposed if not optimized out.
5647   if (Triple.isOSBinFormatELF()) {
5648     Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5649                              options::OPT_fno_semantic_interposition);
5650     if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5651       // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5652       bool SupportsLocalAlias =
5653           Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5654       if (!A)
5655         CmdArgs.push_back("-fhalf-no-semantic-interposition");
5656       else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5657         A->render(Args, CmdArgs);
5658       else if (!SupportsLocalAlias)
5659         CmdArgs.push_back("-fhalf-no-semantic-interposition");
5660     }
5661   }
5662 
5663   {
5664     std::string Model;
5665     if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5666       if (!TC.isThreadModelSupported(A->getValue()))
5667         D.Diag(diag::err_drv_invalid_thread_model_for_target)
5668             << A->getValue() << A->getAsString(Args);
5669       Model = A->getValue();
5670     } else
5671       Model = TC.getThreadModel();
5672     if (Model != "posix") {
5673       CmdArgs.push_back("-mthread-model");
5674       CmdArgs.push_back(Args.MakeArgString(Model));
5675     }
5676   }
5677 
5678   if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5679     StringRef Name = A->getValue();
5680     if (Name == "SVML") {
5681       if (Triple.getArch() != llvm::Triple::x86 &&
5682           Triple.getArch() != llvm::Triple::x86_64)
5683         D.Diag(diag::err_drv_unsupported_opt_for_target)
5684             << Name << Triple.getArchName();
5685     } else if (Name == "AMDLIBM") {
5686       if (Triple.getArch() != llvm::Triple::x86 &&
5687           Triple.getArch() != llvm::Triple::x86_64)
5688         D.Diag(diag::err_drv_unsupported_opt_for_target)
5689             << Name << Triple.getArchName();
5690     } else if (Name == "libmvec") {
5691       if (Triple.getArch() != llvm::Triple::x86 &&
5692           Triple.getArch() != llvm::Triple::x86_64 &&
5693           Triple.getArch() != llvm::Triple::aarch64 &&
5694           Triple.getArch() != llvm::Triple::aarch64_be)
5695         D.Diag(diag::err_drv_unsupported_opt_for_target)
5696             << Name << Triple.getArchName();
5697     } else if (Name == "SLEEF" || Name == "ArmPL") {
5698       if (Triple.getArch() != llvm::Triple::aarch64 &&
5699           Triple.getArch() != llvm::Triple::aarch64_be &&
5700           Triple.getArch() != llvm::Triple::riscv64)
5701         D.Diag(diag::err_drv_unsupported_opt_for_target)
5702             << Name << Triple.getArchName();
5703     }
5704     A->render(Args, CmdArgs);
5705   }
5706 
5707   if (Args.hasFlag(options::OPT_fmerge_all_constants,
5708                    options::OPT_fno_merge_all_constants, false))
5709     CmdArgs.push_back("-fmerge-all-constants");
5710 
5711   Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5712                      options::OPT_fno_delete_null_pointer_checks);
5713 
5714   // LLVM Code Generator Options.
5715 
5716   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5717     if (!Triple.isOSAIX() || Triple.isPPC32())
5718       D.Diag(diag::err_drv_unsupported_opt_for_target)
5719         << A->getSpelling() << RawTriple.str();
5720     CmdArgs.push_back("-mabi=quadword-atomics");
5721   }
5722 
5723   if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5724     // Emit the unsupported option error until the Clang's library integration
5725     // support for 128-bit long double is available for AIX.
5726     if (Triple.isOSAIX())
5727       D.Diag(diag::err_drv_unsupported_opt_for_target)
5728           << A->getSpelling() << RawTriple.str();
5729   }
5730 
5731   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5732     StringRef V = A->getValue(), V1 = V;
5733     unsigned Size;
5734     if (V1.consumeInteger(10, Size) || !V1.empty())
5735       D.Diag(diag::err_drv_invalid_argument_to_option)
5736           << V << A->getOption().getName();
5737     else
5738       CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
5739   }
5740 
5741   Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
5742                      options::OPT_fno_jump_tables);
5743   Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
5744                     options::OPT_fno_profile_sample_accurate);
5745   Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
5746                      options::OPT_fno_preserve_as_comments);
5747 
5748   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5749     CmdArgs.push_back("-mregparm");
5750     CmdArgs.push_back(A->getValue());
5751   }
5752 
5753   if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5754                                options::OPT_msvr4_struct_return)) {
5755     if (!TC.getTriple().isPPC32()) {
5756       D.Diag(diag::err_drv_unsupported_opt_for_target)
5757           << A->getSpelling() << RawTriple.str();
5758     } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5759       CmdArgs.push_back("-maix-struct-return");
5760     } else {
5761       assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5762       CmdArgs.push_back("-msvr4-struct-return");
5763     }
5764   }
5765 
5766   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5767                                options::OPT_freg_struct_return)) {
5768     if (TC.getArch() != llvm::Triple::x86) {
5769       D.Diag(diag::err_drv_unsupported_opt_for_target)
5770           << A->getSpelling() << RawTriple.str();
5771     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5772       CmdArgs.push_back("-fpcc-struct-return");
5773     } else {
5774       assert(A->getOption().matches(options::OPT_freg_struct_return));
5775       CmdArgs.push_back("-freg-struct-return");
5776     }
5777   }
5778 
5779   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
5780     if (Triple.getArch() == llvm::Triple::m68k)
5781       CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
5782     else
5783       CmdArgs.push_back("-fdefault-calling-conv=stdcall");
5784   }
5785 
5786   if (Args.hasArg(options::OPT_fenable_matrix)) {
5787     // enable-matrix is needed by both the LangOpts and by LLVM.
5788     CmdArgs.push_back("-fenable-matrix");
5789     CmdArgs.push_back("-mllvm");
5790     CmdArgs.push_back("-enable-matrix");
5791   }
5792 
5793   CodeGenOptions::FramePointerKind FPKeepKind =
5794                   getFramePointerKind(Args, RawTriple);
5795   const char *FPKeepKindStr = nullptr;
5796   switch (FPKeepKind) {
5797   case CodeGenOptions::FramePointerKind::None:
5798     FPKeepKindStr = "-mframe-pointer=none";
5799     break;
5800   case CodeGenOptions::FramePointerKind::Reserved:
5801     FPKeepKindStr = "-mframe-pointer=reserved";
5802     break;
5803   case CodeGenOptions::FramePointerKind::NonLeaf:
5804     FPKeepKindStr = "-mframe-pointer=non-leaf";
5805     break;
5806   case CodeGenOptions::FramePointerKind::All:
5807     FPKeepKindStr = "-mframe-pointer=all";
5808     break;
5809   }
5810   assert(FPKeepKindStr && "unknown FramePointerKind");
5811   CmdArgs.push_back(FPKeepKindStr);
5812 
5813   Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
5814                      options::OPT_fno_zero_initialized_in_bss);
5815 
5816   bool OFastEnabled = isOptimizationLevelFast(Args);
5817   if (OFastEnabled)
5818     D.Diag(diag::warn_drv_deprecated_arg_ofast);
5819   // If -Ofast is the optimization level, then -fstrict-aliasing should be
5820   // enabled.  This alias option is being used to simplify the hasFlag logic.
5821   OptSpecifier StrictAliasingAliasOption =
5822       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5823   // We turn strict aliasing off by default if we're Windows MSVC since MSVC
5824   // doesn't do any TBAA.
5825   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
5826                     options::OPT_fno_strict_aliasing,
5827                     !IsWindowsMSVC && !IsUEFI))
5828     CmdArgs.push_back("-relaxed-aliasing");
5829   if (Args.hasFlag(options::OPT_fno_pointer_tbaa, options::OPT_fpointer_tbaa,
5830                    false))
5831     CmdArgs.push_back("-no-pointer-tbaa");
5832   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
5833                     options::OPT_fno_struct_path_tbaa, true))
5834     CmdArgs.push_back("-no-struct-path-tbaa");
5835   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
5836                     options::OPT_fno_strict_enums);
5837   Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
5838                      options::OPT_fno_strict_return);
5839   Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
5840                     options::OPT_fno_allow_editor_placeholders);
5841   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
5842                     options::OPT_fno_strict_vtable_pointers);
5843   Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
5844                     options::OPT_fno_force_emit_vtables);
5845   Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5846                      options::OPT_fno_optimize_sibling_calls);
5847   Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
5848                      options::OPT_fno_escaping_block_tail_calls);
5849 
5850   Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
5851                   options::OPT_fno_fine_grained_bitfield_accesses);
5852 
5853   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5854                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
5855 
5856   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
5857                   options::OPT_fno_experimental_omit_vtable_rtti);
5858 
5859   Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,
5860                   options::OPT_fno_disable_block_signature_string);
5861 
5862   // Handle segmented stacks.
5863   Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
5864                     options::OPT_fno_split_stack);
5865 
5866   // -fprotect-parens=0 is default.
5867   if (Args.hasFlag(options::OPT_fprotect_parens,
5868                    options::OPT_fno_protect_parens, false))
5869     CmdArgs.push_back("-fprotect-parens");
5870 
5871   RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5872 
5873   Args.addOptInFlag(CmdArgs, options::OPT_fatomic_remote_memory,
5874                     options::OPT_fno_atomic_remote_memory);
5875   Args.addOptInFlag(CmdArgs, options::OPT_fatomic_fine_grained_memory,
5876                     options::OPT_fno_atomic_fine_grained_memory);
5877   Args.addOptInFlag(CmdArgs, options::OPT_fatomic_ignore_denormal_mode,
5878                     options::OPT_fno_atomic_ignore_denormal_mode);
5879 
5880   if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5881     const llvm::Triple::ArchType Arch = TC.getArch();
5882     if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5883       StringRef V = A->getValue();
5884       if (V == "64")
5885         CmdArgs.push_back("-fextend-arguments=64");
5886       else if (V != "32")
5887         D.Diag(diag::err_drv_invalid_argument_to_option)
5888             << A->getValue() << A->getOption().getName();
5889     } else
5890       D.Diag(diag::err_drv_unsupported_opt_for_target)
5891           << A->getOption().getName() << TripleStr;
5892   }
5893 
5894   if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
5895     if (TC.getArch() == llvm::Triple::avr)
5896       A->render(Args, CmdArgs);
5897     else
5898       D.Diag(diag::err_drv_unsupported_opt_for_target)
5899           << A->getAsString(Args) << TripleStr;
5900   }
5901 
5902   if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5903     if (TC.getTriple().isX86())
5904       A->render(Args, CmdArgs);
5905     else if (TC.getTriple().isPPC() &&
5906              (A->getOption().getID() != options::OPT_mlong_double_80))
5907       A->render(Args, CmdArgs);
5908     else
5909       D.Diag(diag::err_drv_unsupported_opt_for_target)
5910           << A->getAsString(Args) << TripleStr;
5911   }
5912 
5913   // Decide whether to use verbose asm. Verbose assembly is the default on
5914   // toolchains which have the integrated assembler on by default.
5915   bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5916   if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5917                     IsIntegratedAssemblerDefault))
5918     CmdArgs.push_back("-fno-verbose-asm");
5919 
5920   // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5921   // use that to indicate the MC default in the backend.
5922   if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5923     StringRef V = A->getValue();
5924     unsigned Num;
5925     if (V == "none")
5926       A->render(Args, CmdArgs);
5927     else if (!V.consumeInteger(10, Num) && Num > 0 &&
5928              (V.empty() || (V.consume_front(".") &&
5929                             !V.consumeInteger(10, Num) && V.empty())))
5930       A->render(Args, CmdArgs);
5931     else
5932       D.Diag(diag::err_drv_invalid_argument_to_option)
5933           << A->getValue() << A->getOption().getName();
5934   }
5935 
5936   // If toolchain choose to use MCAsmParser for inline asm don't pass the
5937   // option to disable integrated-as explicitly.
5938   if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5939     CmdArgs.push_back("-no-integrated-as");
5940 
5941   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
5942     CmdArgs.push_back("-mdebug-pass");
5943     CmdArgs.push_back("Structure");
5944   }
5945   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
5946     CmdArgs.push_back("-mdebug-pass");
5947     CmdArgs.push_back("Arguments");
5948   }
5949 
5950   // Enable -mconstructor-aliases except on darwin, where we have to work around
5951   // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
5952   // code, where aliases aren't supported.
5953   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5954     CmdArgs.push_back("-mconstructor-aliases");
5955 
5956   // Darwin's kernel doesn't support guard variables; just die if we
5957   // try to use them.
5958   if (KernelOrKext && RawTriple.isOSDarwin())
5959     CmdArgs.push_back("-fforbid-guard-variables");
5960 
5961   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
5962                    Triple.isWindowsGNUEnvironment())) {
5963     CmdArgs.push_back("-mms-bitfields");
5964   }
5965 
5966   if (Triple.isWindowsGNUEnvironment()) {
5967     Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
5968                        options::OPT_fno_auto_import);
5969   }
5970 
5971   if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
5972                    Triple.isX86() && IsWindowsMSVC))
5973     CmdArgs.push_back("-fms-volatile");
5974 
5975   // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5976   // defaults to -fno-direct-access-external-data. Pass the option if different
5977   // from the default.
5978   if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
5979                                options::OPT_fno_direct_access_external_data)) {
5980     if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5981         (PICLevel == 0))
5982       A->render(Args, CmdArgs);
5983   } else if (PICLevel == 0 && Triple.isLoongArch()) {
5984     // Some targets default to -fno-direct-access-external-data even for
5985     // -fno-pic.
5986     CmdArgs.push_back("-fno-direct-access-external-data");
5987   }
5988 
5989   if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
5990     Args.addOptOutFlag(CmdArgs, options::OPT_fplt, options::OPT_fno_plt);
5991 
5992   // -fhosted is default.
5993   // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5994   // use Freestanding.
5995   bool Freestanding =
5996       Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5997       KernelOrKext;
5998   if (Freestanding)
5999     CmdArgs.push_back("-ffreestanding");
6000 
6001   Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
6002 
6003   // This is a coarse approximation of what llvm-gcc actually does, both
6004   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6005   // complicated ways.
6006   auto SanitizeArgs = TC.getSanitizerArgs(Args);
6007   Args.AddLastArg(CmdArgs,
6008                   options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6009   bool IsAsyncUnwindTablesDefault =
6010       TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
6011   bool IsSyncUnwindTablesDefault =
6012       TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
6013 
6014   bool AsyncUnwindTables = Args.hasFlag(
6015       options::OPT_fasynchronous_unwind_tables,
6016       options::OPT_fno_asynchronous_unwind_tables,
6017       (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6018           !Freestanding);
6019   bool UnwindTables =
6020       Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
6021                    IsSyncUnwindTablesDefault && !Freestanding);
6022   if (AsyncUnwindTables)
6023     CmdArgs.push_back("-funwind-tables=2");
6024   else if (UnwindTables)
6025      CmdArgs.push_back("-funwind-tables=1");
6026 
6027   // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6028   // `--gpu-use-aux-triple-only` is specified.
6029   if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
6030       (IsCudaDevice || IsHIPDevice || IsSYCLDevice)) {
6031     const ArgList &HostArgs =
6032         C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
6033     std::string HostCPU =
6034         getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
6035     if (!HostCPU.empty()) {
6036       CmdArgs.push_back("-aux-target-cpu");
6037       CmdArgs.push_back(Args.MakeArgString(HostCPU));
6038     }
6039     getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
6040                       /*ForAS*/ false, /*IsAux*/ true);
6041   }
6042 
6043   TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
6044 
6045   addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6046 
6047   if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
6048     StringRef Value = A->getValue();
6049     unsigned TLSSize = 0;
6050     Value.getAsInteger(10, TLSSize);
6051     if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6052       D.Diag(diag::err_drv_unsupported_opt_for_target)
6053           << A->getOption().getName() << TripleStr;
6054     if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6055       D.Diag(diag::err_drv_invalid_int_value)
6056           << A->getOption().getName() << Value;
6057     Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
6058   }
6059 
6060   if (isTLSDESCEnabled(TC, Args))
6061     CmdArgs.push_back("-enable-tlsdesc");
6062 
6063   // Add the target cpu
6064   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
6065   if (!CPU.empty()) {
6066     CmdArgs.push_back("-target-cpu");
6067     CmdArgs.push_back(Args.MakeArgString(CPU));
6068   }
6069 
6070   RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
6071 
6072   // Add clang-cl arguments.
6073   types::ID InputType = Input.getType();
6074   if (D.IsCLMode())
6075     AddClangCLArgs(Args, InputType, CmdArgs);
6076 
6077   llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6078       llvm::codegenoptions::NoDebugInfo;
6079   DwarfFissionKind DwarfFission = DwarfFissionKind::None;
6080   renderDebugOptions(TC, D, RawTriple, Args, types::isLLVMIR(InputType),
6081                      CmdArgs, Output, DebugInfoKind, DwarfFission);
6082 
6083   // Add the split debug info name to the command lines here so we
6084   // can propagate it to the backend.
6085   bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6086                     (TC.getTriple().isOSBinFormatELF() ||
6087                      TC.getTriple().isOSBinFormatWasm() ||
6088                      TC.getTriple().isOSBinFormatCOFF()) &&
6089                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
6090                      isa<BackendJobAction>(JA));
6091   if (SplitDWARF) {
6092     const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6093     CmdArgs.push_back("-split-dwarf-file");
6094     CmdArgs.push_back(SplitDWARFOut);
6095     if (DwarfFission == DwarfFissionKind::Split) {
6096       CmdArgs.push_back("-split-dwarf-output");
6097       CmdArgs.push_back(SplitDWARFOut);
6098     }
6099   }
6100 
6101   // Pass the linker version in use.
6102   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6103     CmdArgs.push_back("-target-linker-version");
6104     CmdArgs.push_back(A->getValue());
6105   }
6106 
6107   // Explicitly error on some things we know we don't support and can't just
6108   // ignore.
6109   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
6110     Arg *Unsupported;
6111     if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
6112         TC.getArch() == llvm::Triple::x86) {
6113       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
6114           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
6115         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6116             << Unsupported->getOption().getName();
6117     }
6118     // The faltivec option has been superseded by the maltivec option.
6119     if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
6120       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6121           << Unsupported->getOption().getName()
6122           << "please use -maltivec and include altivec.h explicitly";
6123     if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
6124       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6125           << Unsupported->getOption().getName() << "please use -mno-altivec";
6126   }
6127 
6128   Args.AddAllArgs(CmdArgs, options::OPT_v);
6129 
6130   if (Args.getLastArg(options::OPT_H)) {
6131     CmdArgs.push_back("-H");
6132     CmdArgs.push_back("-sys-header-deps");
6133   }
6134   Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
6135 
6136   if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
6137     CmdArgs.push_back("-header-include-file");
6138     CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
6139                           ? D.CCPrintHeadersFilename.c_str()
6140                           : "-");
6141     CmdArgs.push_back("-sys-header-deps");
6142     CmdArgs.push_back(Args.MakeArgString(
6143         "-header-include-format=" +
6144         std::string(headerIncludeFormatKindToString(D.CCPrintHeadersFormat))));
6145     CmdArgs.push_back(
6146         Args.MakeArgString("-header-include-filtering=" +
6147                            std::string(headerIncludeFilteringKindToString(
6148                                D.CCPrintHeadersFiltering))));
6149   }
6150   Args.AddLastArg(CmdArgs, options::OPT_P);
6151   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
6152 
6153   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6154     CmdArgs.push_back("-diagnostic-log-file");
6155     CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
6156                           ? D.CCLogDiagnosticsFilename.c_str()
6157                           : "-");
6158   }
6159 
6160   // Give the gen diagnostics more chances to succeed, by avoiding intentional
6161   // crashes.
6162   if (D.CCGenDiagnostics)
6163     CmdArgs.push_back("-disable-pragma-debug-crash");
6164 
6165   // Allow backend to put its diagnostic files in the same place as frontend
6166   // crash diagnostics files.
6167   if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
6168     StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
6169     CmdArgs.push_back("-mllvm");
6170     CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
6171   }
6172 
6173   bool UseSeparateSections = isUseSeparateSections(Triple);
6174 
6175   if (Args.hasFlag(options::OPT_ffunction_sections,
6176                    options::OPT_fno_function_sections, UseSeparateSections)) {
6177     CmdArgs.push_back("-ffunction-sections");
6178   }
6179 
6180   if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
6181                                options::OPT_fno_basic_block_address_map)) {
6182     if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6183       if (A->getOption().matches(options::OPT_fbasic_block_address_map))
6184         A->render(Args, CmdArgs);
6185     } else {
6186       D.Diag(diag::err_drv_unsupported_opt_for_target)
6187           << A->getAsString(Args) << TripleStr;
6188     }
6189   }
6190 
6191   if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
6192     StringRef Val = A->getValue();
6193     if (Val == "labels") {
6194       D.Diag(diag::warn_drv_deprecated_arg)
6195           << A->getAsString(Args) << /*hasReplacement=*/true
6196           << "-fbasic-block-address-map";
6197       CmdArgs.push_back("-fbasic-block-address-map");
6198     } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6199       if (Val != "all" && Val != "none" && !Val.starts_with("list="))
6200         D.Diag(diag::err_drv_invalid_value)
6201             << A->getAsString(Args) << A->getValue();
6202       else
6203         A->render(Args, CmdArgs);
6204     } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6205       // "all" is not supported on AArch64 since branch relaxation creates new
6206       // basic blocks for some cross-section branches.
6207       if (Val != "labels" && Val != "none" && !Val.starts_with("list="))
6208         D.Diag(diag::err_drv_invalid_value)
6209             << A->getAsString(Args) << A->getValue();
6210       else
6211         A->render(Args, CmdArgs);
6212     } else if (Triple.isNVPTX()) {
6213       // Do not pass the option to the GPU compilation. We still want it enabled
6214       // for the host-side compilation, so seeing it here is not an error.
6215     } else if (Val != "none") {
6216       // =none is allowed everywhere. It's useful for overriding the option
6217       // and is the same as not specifying the option.
6218       D.Diag(diag::err_drv_unsupported_opt_for_target)
6219           << A->getAsString(Args) << TripleStr;
6220     }
6221   }
6222 
6223   bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
6224   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
6225                    UseSeparateSections || HasDefaultDataSections)) {
6226     CmdArgs.push_back("-fdata-sections");
6227   }
6228 
6229   Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
6230                      options::OPT_fno_unique_section_names);
6231   Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,
6232                     options::OPT_fno_separate_named_sections);
6233   Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
6234                     options::OPT_fno_unique_internal_linkage_names);
6235   Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
6236                     options::OPT_fno_unique_basic_block_section_names);
6237 
6238   if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
6239                                options::OPT_fno_split_machine_functions)) {
6240     if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {
6241       // This codegen pass is only available on x86 and AArch64 ELF targets.
6242       if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
6243         A->render(Args, CmdArgs);
6244       else
6245         D.Diag(diag::err_drv_unsupported_opt_for_target)
6246             << A->getAsString(Args) << TripleStr;
6247     }
6248   }
6249 
6250   Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
6251                   options::OPT_finstrument_functions_after_inlining,
6252                   options::OPT_finstrument_function_entry_bare);
6253   Args.AddLastArg(CmdArgs, options::OPT_fconvergent_functions,
6254                   options::OPT_fno_convergent_functions);
6255 
6256   // NVPTX doesn't support PGO or coverage
6257   if (!Triple.isNVPTX())
6258     addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
6259 
6260   Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
6261 
6262   if (getLastProfileSampleUseArg(Args) &&
6263       Args.hasFlag(options::OPT_fsample_profile_use_profi,
6264                    options::OPT_fno_sample_profile_use_profi, true)) {
6265     CmdArgs.push_back("-mllvm");
6266     CmdArgs.push_back("-sample-profile-use-profi");
6267   }
6268 
6269   // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6270   if (RawTriple.isPS() &&
6271       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6272     PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6273     PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6274   }
6275 
6276   // Pass options for controlling the default header search paths.
6277   if (Args.hasArg(options::OPT_nostdinc)) {
6278     CmdArgs.push_back("-nostdsysteminc");
6279     CmdArgs.push_back("-nobuiltininc");
6280   } else {
6281     if (Args.hasArg(options::OPT_nostdlibinc))
6282       CmdArgs.push_back("-nostdsysteminc");
6283     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
6284     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
6285   }
6286 
6287   // Pass the path to compiler resource files.
6288   CmdArgs.push_back("-resource-dir");
6289   CmdArgs.push_back(D.ResourceDir.c_str());
6290 
6291   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
6292 
6293   // Add preprocessing options like -I, -D, etc. if we are using the
6294   // preprocessor.
6295   //
6296   // FIXME: Support -fpreprocessed
6297   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
6298     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6299 
6300   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6301   // that "The compiler can only warn and ignore the option if not recognized".
6302   // When building with ccache, it will pass -D options to clang even on
6303   // preprocessed inputs and configure concludes that -fPIC is not supported.
6304   Args.ClaimAllArgs(options::OPT_D);
6305 
6306   // Warn about ignored options to clang.
6307   for (const Arg *A :
6308        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6309     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6310     A->claim();
6311   }
6312 
6313   for (const Arg *A :
6314        Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6315     D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6316     A->claim();
6317   }
6318 
6319   claimNoWarnArgs(Args);
6320 
6321   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6322 
6323   for (const Arg *A :
6324        Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6325     A->claim();
6326     if (A->getOption().getID() == options::OPT__SLASH_wd) {
6327       unsigned WarningNumber;
6328       if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6329         D.Diag(diag::err_drv_invalid_int_value)
6330             << A->getAsString(Args) << A->getValue();
6331         continue;
6332       }
6333 
6334       if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6335         CmdArgs.push_back(Args.MakeArgString(
6336             "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6337       }
6338       continue;
6339     }
6340     A->render(Args, CmdArgs);
6341   }
6342 
6343   Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6344 
6345   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6346     CmdArgs.push_back("-pedantic");
6347   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6348   Args.AddLastArg(CmdArgs, options::OPT_w);
6349 
6350   Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6351                     options::OPT_fno_fixed_point);
6352 
6353   if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6354     A->render(Args, CmdArgs);
6355 
6356   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6357                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
6358 
6359   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6360                   options::OPT_fno_experimental_omit_vtable_rtti);
6361 
6362   if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6363     A->render(Args, CmdArgs);
6364 
6365   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6366   // (-ansi is equivalent to -std=c89 or -std=c++98).
6367   //
6368   // If a std is supplied, only add -trigraphs if it follows the
6369   // option.
6370   bool ImplyVCPPCVer = false;
6371   bool ImplyVCPPCXXVer = false;
6372   const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6373   if (Std) {
6374     if (Std->getOption().matches(options::OPT_ansi))
6375       if (types::isCXX(InputType))
6376         CmdArgs.push_back("-std=c++98");
6377       else
6378         CmdArgs.push_back("-std=c89");
6379     else
6380       Std->render(Args, CmdArgs);
6381 
6382     // If -f(no-)trigraphs appears after the language standard flag, honor it.
6383     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6384                                  options::OPT_ftrigraphs,
6385                                  options::OPT_fno_trigraphs))
6386       if (A != Std)
6387         A->render(Args, CmdArgs);
6388   } else {
6389     // Honor -std-default.
6390     //
6391     // FIXME: Clang doesn't correctly handle -std= when the input language
6392     // doesn't match. For the time being just ignore this for C++ inputs;
6393     // eventually we want to do all the standard defaulting here instead of
6394     // splitting it between the driver and clang -cc1.
6395     if (!types::isCXX(InputType)) {
6396       if (!Args.hasArg(options::OPT__SLASH_std)) {
6397         Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6398                                   /*Joined=*/true);
6399       } else
6400         ImplyVCPPCVer = true;
6401     }
6402     else if (IsWindowsMSVC)
6403       ImplyVCPPCXXVer = true;
6404 
6405     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6406                     options::OPT_fno_trigraphs);
6407   }
6408 
6409   // GCC's behavior for -Wwrite-strings is a bit strange:
6410   //  * In C, this "warning flag" changes the types of string literals from
6411   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6412   //    for the discarded qualifier.
6413   //  * In C++, this is just a normal warning flag.
6414   //
6415   // Implementing this warning correctly in C is hard, so we follow GCC's
6416   // behavior for now. FIXME: Directly diagnose uses of a string literal as
6417   // a non-const char* in C, rather than using this crude hack.
6418   if (!types::isCXX(InputType)) {
6419     // FIXME: This should behave just like a warning flag, and thus should also
6420     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6421     Arg *WriteStrings =
6422         Args.getLastArg(options::OPT_Wwrite_strings,
6423                         options::OPT_Wno_write_strings, options::OPT_w);
6424     if (WriteStrings &&
6425         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6426       CmdArgs.push_back("-fconst-strings");
6427   }
6428 
6429   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6430   // during C++ compilation, which it is by default. GCC keeps this define even
6431   // in the presence of '-w', match this behavior bug-for-bug.
6432   if (types::isCXX(InputType) &&
6433       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6434                    true)) {
6435     CmdArgs.push_back("-fdeprecated-macro");
6436   }
6437 
6438   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6439   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6440     if (Asm->getOption().matches(options::OPT_fasm))
6441       CmdArgs.push_back("-fgnu-keywords");
6442     else
6443       CmdArgs.push_back("-fno-gnu-keywords");
6444   }
6445 
6446   if (!ShouldEnableAutolink(Args, TC, JA))
6447     CmdArgs.push_back("-fno-autolink");
6448 
6449   Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6450   Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6451   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6452   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6453 
6454   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6455 
6456   if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
6457     CmdArgs.push_back("-fexperimental-new-constant-interpreter");
6458 
6459   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6460     CmdArgs.push_back("-fbracket-depth");
6461     CmdArgs.push_back(A->getValue());
6462   }
6463 
6464   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6465                                options::OPT_Wlarge_by_value_copy_def)) {
6466     if (A->getNumValues()) {
6467       StringRef bytes = A->getValue();
6468       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6469     } else
6470       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6471   }
6472 
6473   if (Args.hasArg(options::OPT_relocatable_pch))
6474     CmdArgs.push_back("-relocatable-pch");
6475 
6476   if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6477     static const char *kCFABIs[] = {
6478       "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6479     };
6480 
6481     if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6482       D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6483     else
6484       A->render(Args, CmdArgs);
6485   }
6486 
6487   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6488     CmdArgs.push_back("-fconstant-string-class");
6489     CmdArgs.push_back(A->getValue());
6490   }
6491 
6492   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6493     CmdArgs.push_back("-ftabstop");
6494     CmdArgs.push_back(A->getValue());
6495   }
6496 
6497   Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6498                     options::OPT_fno_stack_size_section);
6499 
6500   if (Args.hasArg(options::OPT_fstack_usage)) {
6501     CmdArgs.push_back("-stack-usage-file");
6502 
6503     if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6504       SmallString<128> OutputFilename(OutputOpt->getValue());
6505       llvm::sys::path::replace_extension(OutputFilename, "su");
6506       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6507     } else
6508       CmdArgs.push_back(
6509           Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6510   }
6511 
6512   CmdArgs.push_back("-ferror-limit");
6513   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6514     CmdArgs.push_back(A->getValue());
6515   else
6516     CmdArgs.push_back("19");
6517 
6518   Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6519   Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6520   Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6521   Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6522   Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6523 
6524   // Pass -fmessage-length=.
6525   unsigned MessageLength = 0;
6526   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6527     StringRef V(A->getValue());
6528     if (V.getAsInteger(0, MessageLength))
6529       D.Diag(diag::err_drv_invalid_argument_to_option)
6530           << V << A->getOption().getName();
6531   } else {
6532     // If -fmessage-length=N was not specified, determine whether this is a
6533     // terminal and, if so, implicitly define -fmessage-length appropriately.
6534     MessageLength = llvm::sys::Process::StandardErrColumns();
6535   }
6536   if (MessageLength != 0)
6537     CmdArgs.push_back(
6538         Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6539 
6540   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6541     CmdArgs.push_back(
6542         Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
6543 
6544   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6545     CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
6546                                          Twine(A->getValue(0))));
6547 
6548   // -fvisibility= and -fvisibility-ms-compat are of a piece.
6549   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6550                                      options::OPT_fvisibility_ms_compat)) {
6551     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6552       A->render(Args, CmdArgs);
6553     } else {
6554       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6555       CmdArgs.push_back("-fvisibility=hidden");
6556       CmdArgs.push_back("-ftype-visibility=default");
6557     }
6558   } else if (IsOpenMPDevice) {
6559     // When compiling for the OpenMP device we want protected visibility by
6560     // default. This prevents the device from accidentally preempting code on
6561     // the host, makes the system more robust, and improves performance.
6562     CmdArgs.push_back("-fvisibility=protected");
6563   }
6564 
6565   // PS4/PS5 process these options in addClangTargetOptions.
6566   if (!RawTriple.isPS()) {
6567     if (const Arg *A =
6568             Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6569                             options::OPT_fno_visibility_from_dllstorageclass)) {
6570       if (A->getOption().matches(
6571               options::OPT_fvisibility_from_dllstorageclass)) {
6572         CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6573         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6574         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6575         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6576         Args.AddLastArg(CmdArgs,
6577                         options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6578       }
6579     }
6580   }
6581 
6582   if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6583                     options::OPT_fno_visibility_inlines_hidden, false))
6584     CmdArgs.push_back("-fvisibility-inlines-hidden");
6585 
6586   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6587                            options::OPT_fno_visibility_inlines_hidden_static_local_var);
6588 
6589   // -fvisibility-global-new-delete-hidden is a deprecated spelling of
6590   // -fvisibility-global-new-delete=force-hidden.
6591   if (const Arg *A =
6592           Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
6593     D.Diag(diag::warn_drv_deprecated_arg)
6594         << A->getAsString(Args) << /*hasReplacement=*/true
6595         << "-fvisibility-global-new-delete=force-hidden";
6596   }
6597 
6598   if (const Arg *A =
6599           Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
6600                           options::OPT_fvisibility_global_new_delete_hidden)) {
6601     if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
6602       A->render(Args, CmdArgs);
6603     } else {
6604       assert(A->getOption().matches(
6605           options::OPT_fvisibility_global_new_delete_hidden));
6606       CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");
6607     }
6608   }
6609 
6610   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
6611 
6612   if (Args.hasFlag(options::OPT_fnew_infallible,
6613                    options::OPT_fno_new_infallible, false))
6614     CmdArgs.push_back("-fnew-infallible");
6615 
6616   if (Args.hasFlag(options::OPT_fno_operator_names,
6617                    options::OPT_foperator_names, false))
6618     CmdArgs.push_back("-fno-operator-names");
6619 
6620   // Forward -f (flag) options which we can pass directly.
6621   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
6622   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
6623   Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
6624   Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
6625   Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,
6626                   options::OPT_fno_raw_string_literals);
6627 
6628   if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
6629                    Triple.hasDefaultEmulatedTLS()))
6630     CmdArgs.push_back("-femulated-tls");
6631 
6632   Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
6633                     options::OPT_fno_check_new);
6634 
6635   if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
6636     // FIXME: There's no reason for this to be restricted to X86. The backend
6637     // code needs to be changed to include the appropriate function calls
6638     // automatically.
6639     if (!Triple.isX86() && !Triple.isAArch64())
6640       D.Diag(diag::err_drv_unsupported_opt_for_target)
6641           << A->getAsString(Args) << TripleStr;
6642   }
6643 
6644   // AltiVec-like language extensions aren't relevant for assembling.
6645   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
6646     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
6647 
6648   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
6649   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
6650 
6651   // Forward flags for OpenMP. We don't do this if the current action is an
6652   // device offloading action other than OpenMP.
6653   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6654                    options::OPT_fno_openmp, false) &&
6655       !Args.hasFlag(options::OPT_foffload_via_llvm,
6656                     options::OPT_fno_offload_via_llvm, false) &&
6657       (JA.isDeviceOffloading(Action::OFK_None) ||
6658        JA.isDeviceOffloading(Action::OFK_OpenMP))) {
6659     switch (D.getOpenMPRuntime(Args)) {
6660     case Driver::OMPRT_OMP:
6661     case Driver::OMPRT_IOMP5:
6662       // Clang can generate useful OpenMP code for these two runtime libraries.
6663       CmdArgs.push_back("-fopenmp");
6664 
6665       // If no option regarding the use of TLS in OpenMP codegeneration is
6666       // given, decide a default based on the target. Otherwise rely on the
6667       // options and pass the right information to the frontend.
6668       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
6669                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6670         CmdArgs.push_back("-fnoopenmp-use-tls");
6671       Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6672                       options::OPT_fno_openmp_simd);
6673       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
6674       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6675       if (!Args.hasFlag(options::OPT_fopenmp_extensions,
6676                         options::OPT_fno_openmp_extensions, /*Default=*/true))
6677         CmdArgs.push_back("-fno-openmp-extensions");
6678       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
6679       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6680       Args.AddAllArgs(CmdArgs,
6681                       options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6682       if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
6683                        options::OPT_fno_openmp_optimistic_collapse,
6684                        /*Default=*/false))
6685         CmdArgs.push_back("-fopenmp-optimistic-collapse");
6686 
6687       // When in OpenMP offloading mode with NVPTX target, forward
6688       // cuda-mode flag
6689       if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
6690                        options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6691         CmdArgs.push_back("-fopenmp-cuda-mode");
6692 
6693       // When in OpenMP offloading mode, enable debugging on the device.
6694       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6695       if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6696                        options::OPT_fno_openmp_target_debug, /*Default=*/false))
6697         CmdArgs.push_back("-fopenmp-target-debug");
6698 
6699       // When in OpenMP offloading mode, forward assumptions information about
6700       // thread and team counts in the device.
6701       if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6702                        options::OPT_fno_openmp_assume_teams_oversubscription,
6703                        /*Default=*/false))
6704         CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
6705       if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6706                        options::OPT_fno_openmp_assume_threads_oversubscription,
6707                        /*Default=*/false))
6708         CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
6709       if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
6710         CmdArgs.push_back("-fopenmp-assume-no-thread-state");
6711       if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
6712         CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
6713       if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
6714         CmdArgs.push_back("-fopenmp-offload-mandatory");
6715       if (Args.hasArg(options::OPT_fopenmp_force_usm))
6716         CmdArgs.push_back("-fopenmp-force-usm");
6717       break;
6718     default:
6719       // By default, if Clang doesn't know how to generate useful OpenMP code
6720       // for a specific runtime library, we just don't pass the '-fopenmp' flag
6721       // down to the actual compilation.
6722       // FIXME: It would be better to have a mode which *only* omits IR
6723       // generation based on the OpenMP support so that we get consistent
6724       // semantic analysis, etc.
6725       break;
6726     }
6727   } else {
6728     Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6729                     options::OPT_fno_openmp_simd);
6730     Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6731     Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
6732                        options::OPT_fno_openmp_extensions);
6733   }
6734   // Forward the offload runtime change to code generation, liboffload implies
6735   // new driver. Otherwise, check if we should forward the new driver to change
6736   // offloading code generation.
6737   if (Args.hasFlag(options::OPT_foffload_via_llvm,
6738                    options::OPT_fno_offload_via_llvm, false)) {
6739     CmdArgs.append({"--offload-new-driver", "-foffload-via-llvm"});
6740   } else if (Args.hasFlag(options::OPT_offload_new_driver,
6741                           options::OPT_no_offload_new_driver,
6742                           C.isOffloadingHostKind(Action::OFK_Cuda))) {
6743     CmdArgs.push_back("--offload-new-driver");
6744   }
6745 
6746   const XRayArgs &XRay = TC.getXRayArgs(Args);
6747   XRay.addArgs(TC, Args, CmdArgs, InputType);
6748 
6749   for (const auto &Filename :
6750        Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6751     if (D.getVFS().exists(Filename))
6752       CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6753     else
6754       D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6755   }
6756 
6757   if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6758     StringRef S0 = A->getValue(), S = S0;
6759     unsigned Size, Offset = 0;
6760     if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
6761         !Triple.isX86() &&
6762         !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
6763                                 Triple.getArch() == llvm::Triple::ppc64)))
6764       D.Diag(diag::err_drv_unsupported_opt_for_target)
6765           << A->getAsString(Args) << TripleStr;
6766     else if (S.consumeInteger(10, Size) ||
6767              (!S.empty() &&
6768               (!S.consume_front(",") || S.consumeInteger(10, Offset))) ||
6769              (!S.empty() && (!S.consume_front(",") || S.empty())))
6770       D.Diag(diag::err_drv_invalid_argument_to_option)
6771           << S0 << A->getOption().getName();
6772     else if (Size < Offset)
6773       D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
6774     else {
6775       CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
6776       CmdArgs.push_back(Args.MakeArgString(
6777           "-fpatchable-function-entry-offset=" + Twine(Offset)));
6778       if (!S.empty())
6779         CmdArgs.push_back(
6780             Args.MakeArgString("-fpatchable-function-entry-section=" + S));
6781     }
6782   }
6783 
6784   Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
6785 
6786   if (Args.hasArg(options::OPT_fms_secure_hotpatch_functions_file))
6787     Args.AddLastArg(CmdArgs, options::OPT_fms_secure_hotpatch_functions_file);
6788 
6789   for (const auto &A :
6790        Args.getAllArgValues(options::OPT_fms_secure_hotpatch_functions_list))
6791     CmdArgs.push_back(
6792         Args.MakeArgString("-fms-secure-hotpatch-functions-list=" + Twine(A)));
6793 
6794   if (TC.SupportsProfiling()) {
6795     Args.AddLastArg(CmdArgs, options::OPT_pg);
6796 
6797     llvm::Triple::ArchType Arch = TC.getArch();
6798     if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
6799       if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6800         A->render(Args, CmdArgs);
6801       else
6802         D.Diag(diag::err_drv_unsupported_opt_for_target)
6803             << A->getAsString(Args) << TripleStr;
6804     }
6805     if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
6806       if (Arch == llvm::Triple::systemz)
6807         A->render(Args, CmdArgs);
6808       else
6809         D.Diag(diag::err_drv_unsupported_opt_for_target)
6810             << A->getAsString(Args) << TripleStr;
6811     }
6812     if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
6813       if (Arch == llvm::Triple::systemz)
6814         A->render(Args, CmdArgs);
6815       else
6816         D.Diag(diag::err_drv_unsupported_opt_for_target)
6817             << A->getAsString(Args) << TripleStr;
6818     }
6819   }
6820 
6821   if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
6822     if (TC.getTriple().isOSzOS()) {
6823       D.Diag(diag::err_drv_unsupported_opt_for_target)
6824           << A->getAsString(Args) << TripleStr;
6825     }
6826   }
6827   if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
6828     if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
6829       D.Diag(diag::err_drv_unsupported_opt_for_target)
6830           << A->getAsString(Args) << TripleStr;
6831     }
6832   }
6833   if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
6834     if (A->getOption().matches(options::OPT_p)) {
6835       A->claim();
6836       if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
6837         CmdArgs.push_back("-pg");
6838     }
6839   }
6840 
6841   // Reject AIX-specific link options on other targets.
6842   if (!TC.getTriple().isOSAIX()) {
6843     for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
6844                                       options::OPT_mxcoff_build_id_EQ)) {
6845       D.Diag(diag::err_drv_unsupported_opt_for_target)
6846           << A->getSpelling() << TripleStr;
6847     }
6848   }
6849 
6850   if (Args.getLastArg(options::OPT_fapple_kext) ||
6851       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
6852     CmdArgs.push_back("-fapple-kext");
6853 
6854   Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
6855   Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
6856   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
6857   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
6858   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
6859   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
6860   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
6861   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_json);
6862   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
6863   Args.AddLastArg(CmdArgs, options::OPT_malign_double);
6864   Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
6865 
6866   if (const char *Name = C.getTimeTraceFile(&JA)) {
6867     CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
6868     Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
6869     Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
6870   }
6871 
6872   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
6873     CmdArgs.push_back("-ftrapv-handler");
6874     CmdArgs.push_back(A->getValue());
6875   }
6876 
6877   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
6878 
6879   // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
6880   // clang and flang.
6881   renderCommonIntegerOverflowOptions(Args, CmdArgs);
6882 
6883   Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
6884                   options::OPT_fno_finite_loops);
6885 
6886   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
6887   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
6888                   options::OPT_fno_unroll_loops);
6889   Args.AddLastArg(CmdArgs, options::OPT_floop_interchange,
6890                   options::OPT_fno_loop_interchange);
6891 
6892   Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
6893 
6894   Args.AddLastArg(CmdArgs, options::OPT_pthread);
6895 
6896   Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
6897                     options::OPT_mno_speculative_load_hardening);
6898 
6899   RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
6900   RenderSCPOptions(TC, Args, CmdArgs);
6901   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
6902 
6903   Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
6904 
6905   Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
6906                     options::OPT_mno_stackrealign);
6907 
6908   if (const Arg *A = Args.getLastArg(options::OPT_mstack_alignment)) {
6909     StringRef Value = A->getValue();
6910     int64_t Alignment = 0;
6911     if (Value.getAsInteger(10, Alignment) || Alignment < 0)
6912       D.Diag(diag::err_drv_invalid_argument_to_option)
6913           << Value << A->getOption().getName();
6914     else if (Alignment & (Alignment - 1))
6915       D.Diag(diag::err_drv_alignment_not_power_of_two)
6916           << A->getAsString(Args) << Value;
6917     else
6918       CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + Value));
6919   }
6920 
6921   if (Args.hasArg(options::OPT_mstack_probe_size)) {
6922     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
6923 
6924     if (!Size.empty())
6925       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
6926     else
6927       CmdArgs.push_back("-mstack-probe-size=0");
6928   }
6929 
6930   Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
6931                      options::OPT_mno_stack_arg_probe);
6932 
6933   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
6934                                options::OPT_mno_restrict_it)) {
6935     if (A->getOption().matches(options::OPT_mrestrict_it)) {
6936       CmdArgs.push_back("-mllvm");
6937       CmdArgs.push_back("-arm-restrict-it");
6938     } else {
6939       CmdArgs.push_back("-mllvm");
6940       CmdArgs.push_back("-arm-default-it");
6941     }
6942   }
6943 
6944   // Forward -cl options to -cc1
6945   RenderOpenCLOptions(Args, CmdArgs, InputType);
6946 
6947   // Forward hlsl options to -cc1
6948   RenderHLSLOptions(Args, CmdArgs, InputType);
6949 
6950   // Forward OpenACC options to -cc1
6951   RenderOpenACCOptions(D, Args, CmdArgs, InputType);
6952 
6953   if (IsHIP) {
6954     if (Args.hasFlag(options::OPT_fhip_new_launch_api,
6955                      options::OPT_fno_hip_new_launch_api, true))
6956       CmdArgs.push_back("-fhip-new-launch-api");
6957     Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
6958                       options::OPT_fno_gpu_allow_device_init);
6959     Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
6960     Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
6961     Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
6962                       options::OPT_fno_hip_kernel_arg_name);
6963   }
6964 
6965   if (IsCuda || IsHIP) {
6966     if (IsRDCMode)
6967       CmdArgs.push_back("-fgpu-rdc");
6968     Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
6969                       options::OPT_fno_gpu_defer_diag);
6970     if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
6971                      options::OPT_fno_gpu_exclude_wrong_side_overloads,
6972                      false)) {
6973       CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
6974       CmdArgs.push_back("-fgpu-defer-diag");
6975     }
6976   }
6977 
6978   // Forward --no-offloadlib to -cc1.
6979   if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))
6980     CmdArgs.push_back("--no-offloadlib");
6981 
6982   if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
6983     CmdArgs.push_back(
6984         Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
6985 
6986     if (Arg *SA = Args.getLastArg(options::OPT_mcf_branch_label_scheme_EQ))
6987       CmdArgs.push_back(Args.MakeArgString(Twine("-mcf-branch-label-scheme=") +
6988                                            SA->getValue()));
6989   } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
6990     // Emit IBT endbr64 instructions by default
6991     CmdArgs.push_back("-fcf-protection=branch");
6992     // jump-table can generate indirect jumps, which are not permitted
6993     CmdArgs.push_back("-fno-jump-tables");
6994   }
6995 
6996   if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
6997     CmdArgs.push_back(
6998         Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
6999 
7000   Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
7001 
7002   // Forward -f options with positive and negative forms; we translate these by
7003   // hand.  Do not propagate PGO options to the GPU-side compilations as the
7004   // profile info is for the host-side compilation only.
7005   if (!(IsCudaDevice || IsHIPDevice)) {
7006     if (Arg *A = getLastProfileSampleUseArg(Args)) {
7007       auto *PGOArg = Args.getLastArg(
7008           options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
7009           options::OPT_fcs_profile_generate,
7010           options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
7011           options::OPT_fprofile_use_EQ);
7012       if (PGOArg)
7013         D.Diag(diag::err_drv_argument_not_allowed_with)
7014             << "SampleUse with PGO options";
7015 
7016       StringRef fname = A->getValue();
7017       if (!llvm::sys::fs::exists(fname))
7018         D.Diag(diag::err_drv_no_such_file) << fname;
7019       else
7020         A->render(Args, CmdArgs);
7021     }
7022     Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
7023 
7024     if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
7025                      options::OPT_fno_pseudo_probe_for_profiling, false)) {
7026       CmdArgs.push_back("-fpseudo-probe-for-profiling");
7027       // Enforce -funique-internal-linkage-names if it's not explicitly turned
7028       // off.
7029       if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
7030                        options::OPT_fno_unique_internal_linkage_names, true))
7031         CmdArgs.push_back("-funique-internal-linkage-names");
7032     }
7033   }
7034   RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
7035 
7036   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7037                      options::OPT_fno_assume_sane_operator_new);
7038 
7039   if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
7040     CmdArgs.push_back("-fapinotes");
7041   if (Args.hasFlag(options::OPT_fapinotes_modules,
7042                    options::OPT_fno_apinotes_modules, false))
7043     CmdArgs.push_back("-fapinotes-modules");
7044   Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
7045 
7046   if (Args.hasFlag(options::OPT_fswift_version_independent_apinotes,
7047                    options::OPT_fno_swift_version_independent_apinotes, false))
7048     CmdArgs.push_back("-fswift-version-independent-apinotes");
7049 
7050   // -fblocks=0 is default.
7051   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
7052                    TC.IsBlocksDefault()) ||
7053       (Args.hasArg(options::OPT_fgnu_runtime) &&
7054        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
7055        !Args.hasArg(options::OPT_fno_blocks))) {
7056     CmdArgs.push_back("-fblocks");
7057 
7058     if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7059       CmdArgs.push_back("-fblocks-runtime-optional");
7060   }
7061 
7062   // -fencode-extended-block-signature=1 is default.
7063   if (TC.IsEncodeExtendedBlockSignatureDefault())
7064     CmdArgs.push_back("-fencode-extended-block-signature");
7065 
7066   if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
7067                    options::OPT_fno_coro_aligned_allocation, false) &&
7068       types::isCXX(InputType))
7069     CmdArgs.push_back("-fcoro-aligned-allocation");
7070 
7071   Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
7072                   options::OPT_fno_double_square_bracket_attributes);
7073 
7074   Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
7075                      options::OPT_fno_access_control);
7076   Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
7077                      options::OPT_fno_elide_constructors);
7078 
7079   ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7080 
7081   if (KernelOrKext || (types::isCXX(InputType) &&
7082                        (RTTIMode == ToolChain::RM_Disabled)))
7083     CmdArgs.push_back("-fno-rtti");
7084 
7085   // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7086   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
7087                    TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7088     CmdArgs.push_back("-fshort-enums");
7089 
7090   RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7091 
7092   // -fuse-cxa-atexit is default.
7093   if (!Args.hasFlag(
7094           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
7095           !RawTriple.isOSAIX() &&
7096               (!RawTriple.isOSWindows() ||
7097                RawTriple.isWindowsCygwinEnvironment()) &&
7098               ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7099                RawTriple.hasEnvironment())) ||
7100       KernelOrKext)
7101     CmdArgs.push_back("-fno-use-cxa-atexit");
7102 
7103   if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
7104                    options::OPT_fno_register_global_dtors_with_atexit,
7105                    RawTriple.isOSDarwin() && !KernelOrKext))
7106     CmdArgs.push_back("-fregister-global-dtors-with-atexit");
7107 
7108   Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
7109                     options::OPT_fno_use_line_directives);
7110 
7111   // -fno-minimize-whitespace is default.
7112   if (Args.hasFlag(options::OPT_fminimize_whitespace,
7113                    options::OPT_fno_minimize_whitespace, false)) {
7114     types::ID InputType = Inputs[0].getType();
7115     if (!isDerivedFromC(InputType))
7116       D.Diag(diag::err_drv_opt_unsupported_input_type)
7117           << "-fminimize-whitespace" << types::getTypeName(InputType);
7118     CmdArgs.push_back("-fminimize-whitespace");
7119   }
7120 
7121   // -fno-keep-system-includes is default.
7122   if (Args.hasFlag(options::OPT_fkeep_system_includes,
7123                    options::OPT_fno_keep_system_includes, false)) {
7124     types::ID InputType = Inputs[0].getType();
7125     if (!isDerivedFromC(InputType))
7126       D.Diag(diag::err_drv_opt_unsupported_input_type)
7127           << "-fkeep-system-includes" << types::getTypeName(InputType);
7128     CmdArgs.push_back("-fkeep-system-includes");
7129   }
7130 
7131   // -fms-extensions=0 is default.
7132   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
7133                    IsWindowsMSVC || IsUEFI))
7134     CmdArgs.push_back("-fms-extensions");
7135 
7136   // -fms-compatibility=0 is default.
7137   bool IsMSVCCompat = Args.hasFlag(
7138       options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
7139       (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
7140                                      options::OPT_fno_ms_extensions, true)));
7141   if (IsMSVCCompat) {
7142     CmdArgs.push_back("-fms-compatibility");
7143     if (!types::isCXX(Input.getType()) &&
7144         Args.hasArg(options::OPT_fms_define_stdc))
7145       CmdArgs.push_back("-fms-define-stdc");
7146   }
7147 
7148   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7149       Args.hasArg(options::OPT_fms_runtime_lib_EQ))
7150     ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
7151 
7152   // Handle -fgcc-version, if present.
7153   VersionTuple GNUCVer;
7154   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
7155     // Check that the version has 1 to 3 components and the minor and patch
7156     // versions fit in two decimal digits.
7157     StringRef Val = A->getValue();
7158     Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7159     bool Invalid = GNUCVer.tryParse(Val);
7160     unsigned Minor = GNUCVer.getMinor().value_or(0);
7161     unsigned Patch = GNUCVer.getSubminor().value_or(0);
7162     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7163       D.Diag(diag::err_drv_invalid_value)
7164           << A->getAsString(Args) << A->getValue();
7165     }
7166   } else if (!IsMSVCCompat) {
7167     // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7168     GNUCVer = VersionTuple(4, 2, 1);
7169   }
7170   if (!GNUCVer.empty()) {
7171     CmdArgs.push_back(
7172         Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
7173   }
7174 
7175   VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
7176   if (!MSVT.empty())
7177     CmdArgs.push_back(
7178         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
7179 
7180   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7181   if (ImplyVCPPCVer) {
7182     StringRef LanguageStandard;
7183     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7184       Std = StdArg;
7185       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7186                              .Case("c11", "-std=c11")
7187                              .Case("c17", "-std=c17")
7188                              // TODO: add c23 when MSVC supports it.
7189                              .Case("clatest", "-std=c23")
7190                              .Default("");
7191       if (LanguageStandard.empty())
7192         D.Diag(clang::diag::warn_drv_unused_argument)
7193             << StdArg->getAsString(Args);
7194     }
7195     CmdArgs.push_back(LanguageStandard.data());
7196   }
7197   if (ImplyVCPPCXXVer) {
7198     StringRef LanguageStandard;
7199     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7200       Std = StdArg;
7201       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7202                              .Case("c++14", "-std=c++14")
7203                              .Case("c++17", "-std=c++17")
7204                              .Case("c++20", "-std=c++20")
7205                              // TODO add c++23 and c++26 when MSVC supports it.
7206                              .Case("c++23preview", "-std=c++23")
7207                              .Case("c++latest", "-std=c++26")
7208                              .Default("");
7209       if (LanguageStandard.empty())
7210         D.Diag(clang::diag::warn_drv_unused_argument)
7211             << StdArg->getAsString(Args);
7212     }
7213 
7214     if (LanguageStandard.empty()) {
7215       if (IsMSVC2015Compatible)
7216         LanguageStandard = "-std=c++14";
7217       else
7218         LanguageStandard = "-std=c++11";
7219     }
7220 
7221     CmdArgs.push_back(LanguageStandard.data());
7222   }
7223 
7224   Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
7225                     options::OPT_fno_borland_extensions);
7226 
7227   // -fno-declspec is default, except for PS4/PS5.
7228   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
7229                    RawTriple.isPS()))
7230     CmdArgs.push_back("-fdeclspec");
7231   else if (Args.hasArg(options::OPT_fno_declspec))
7232     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
7233 
7234   // -fthreadsafe-static is default, except for MSVC compatibility versions less
7235   // than 19.
7236   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
7237                     options::OPT_fno_threadsafe_statics,
7238                     !types::isOpenCL(InputType) &&
7239                         (!IsWindowsMSVC || IsMSVC2015Compatible)))
7240     CmdArgs.push_back("-fno-threadsafe-statics");
7241 
7242   if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,
7243                     true))
7244     CmdArgs.push_back("-fno-ms-tls-guards");
7245 
7246   // Add -fno-assumptions, if it was specified.
7247   if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
7248                     true))
7249     CmdArgs.push_back("-fno-assumptions");
7250 
7251   // -fgnu-keywords default varies depending on language; only pass if
7252   // specified.
7253   Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
7254                   options::OPT_fno_gnu_keywords);
7255 
7256   Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
7257                     options::OPT_fno_gnu89_inline);
7258 
7259   const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
7260                                          options::OPT_finline_hint_functions,
7261                                          options::OPT_fno_inline_functions);
7262   if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
7263     if (A->getOption().matches(options::OPT_fno_inline))
7264       A->render(Args, CmdArgs);
7265   } else if (InlineArg) {
7266     InlineArg->render(Args, CmdArgs);
7267   }
7268 
7269   Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
7270 
7271   // FIXME: Find a better way to determine whether we are in C++20.
7272   bool HaveCxx20 =
7273       Std &&
7274       (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
7275        Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
7276        Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
7277        Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
7278        Std->containsValue("c++2c") || Std->containsValue("gnu++2c") ||
7279        Std->containsValue("c++26") || Std->containsValue("gnu++26") ||
7280        Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
7281   bool HaveModules =
7282       RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
7283 
7284   // -fdelayed-template-parsing is default when targeting MSVC.
7285   // Many old Windows SDK versions require this to parse.
7286   //
7287   // According to
7288   // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7289   // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7290   // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7291   // not enable -fdelayed-template-parsing by default after C++20.
7292   //
7293   // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7294   // able to disable this by default at some point.
7295   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
7296                    options::OPT_fno_delayed_template_parsing,
7297                    IsWindowsMSVC && !HaveCxx20)) {
7298     if (HaveCxx20)
7299       D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7300 
7301     CmdArgs.push_back("-fdelayed-template-parsing");
7302   }
7303 
7304   if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7305                    options::OPT_fno_pch_validate_input_files_content, false))
7306     CmdArgs.push_back("-fvalidate-ast-input-files-content");
7307   if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
7308                    options::OPT_fno_pch_instantiate_templates, false))
7309     CmdArgs.push_back("-fpch-instantiate-templates");
7310   if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7311                    false))
7312     CmdArgs.push_back("-fmodules-codegen");
7313   if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7314                    false))
7315     CmdArgs.push_back("-fmodules-debuginfo");
7316 
7317   ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
7318   RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
7319                     Input, CmdArgs);
7320 
7321   if (types::isObjC(Input.getType()) &&
7322       Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7323                    options::OPT_fno_objc_encode_cxx_class_template_spec,
7324                    !Runtime.isNeXTFamily()))
7325     CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
7326 
7327   if (Args.hasFlag(options::OPT_fapplication_extension,
7328                    options::OPT_fno_application_extension, false))
7329     CmdArgs.push_back("-fapplication-extension");
7330 
7331   // Handle GCC-style exception args.
7332   bool EH = false;
7333   if (!C.getDriver().IsCLMode())
7334     EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
7335 
7336   // Handle exception personalities
7337   Arg *A = Args.getLastArg(
7338       options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7339       options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
7340   if (A) {
7341     const Option &Opt = A->getOption();
7342     if (Opt.matches(options::OPT_fsjlj_exceptions))
7343       CmdArgs.push_back("-exception-model=sjlj");
7344     if (Opt.matches(options::OPT_fseh_exceptions))
7345       CmdArgs.push_back("-exception-model=seh");
7346     if (Opt.matches(options::OPT_fdwarf_exceptions))
7347       CmdArgs.push_back("-exception-model=dwarf");
7348     if (Opt.matches(options::OPT_fwasm_exceptions))
7349       CmdArgs.push_back("-exception-model=wasm");
7350   } else {
7351     switch (TC.GetExceptionModel(Args)) {
7352     default:
7353       break;
7354     case llvm::ExceptionHandling::DwarfCFI:
7355       CmdArgs.push_back("-exception-model=dwarf");
7356       break;
7357     case llvm::ExceptionHandling::SjLj:
7358       CmdArgs.push_back("-exception-model=sjlj");
7359       break;
7360     case llvm::ExceptionHandling::WinEH:
7361       CmdArgs.push_back("-exception-model=seh");
7362       break;
7363     }
7364   }
7365 
7366   // Unwind v2 (epilog) information for x64 Windows.
7367   Args.AddLastArg(CmdArgs, options::OPT_winx64_eh_unwindv2);
7368 
7369   // C++ "sane" operator new.
7370   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7371                      options::OPT_fno_assume_sane_operator_new);
7372 
7373   // -fassume-unique-vtables is on by default.
7374   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
7375                      options::OPT_fno_assume_unique_vtables);
7376 
7377   // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7378   // by default.
7379   Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,
7380                   options::OPT_fno_sized_deallocation);
7381 
7382   // -faligned-allocation is on by default in C++17 onwards and otherwise off
7383   // by default.
7384   if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
7385                                options::OPT_fno_aligned_allocation,
7386                                options::OPT_faligned_new_EQ)) {
7387     if (A->getOption().matches(options::OPT_fno_aligned_allocation))
7388       CmdArgs.push_back("-fno-aligned-allocation");
7389     else
7390       CmdArgs.push_back("-faligned-allocation");
7391   }
7392 
7393   // The default new alignment can be specified using a dedicated option or via
7394   // a GCC-compatible option that also turns on aligned allocation.
7395   if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
7396                                options::OPT_faligned_new_EQ))
7397     CmdArgs.push_back(
7398         Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
7399 
7400   // -fconstant-cfstrings is default, and may be subject to argument translation
7401   // on Darwin.
7402   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
7403                     options::OPT_fno_constant_cfstrings, true) ||
7404       !Args.hasFlag(options::OPT_mconstant_cfstrings,
7405                     options::OPT_mno_constant_cfstrings, true))
7406     CmdArgs.push_back("-fno-constant-cfstrings");
7407 
7408   Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
7409                     options::OPT_fno_pascal_strings);
7410 
7411   // Honor -fpack-struct= and -fpack-struct, if given. Note that
7412   // -fno-pack-struct doesn't apply to -fpack-struct=.
7413   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
7414     std::string PackStructStr = "-fpack-struct=";
7415     PackStructStr += A->getValue();
7416     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
7417   } else if (Args.hasFlag(options::OPT_fpack_struct,
7418                           options::OPT_fno_pack_struct, false)) {
7419     CmdArgs.push_back("-fpack-struct=1");
7420   }
7421 
7422   // Handle -fmax-type-align=N and -fno-type-align
7423   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
7424   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
7425     if (!SkipMaxTypeAlign) {
7426       std::string MaxTypeAlignStr = "-fmax-type-align=";
7427       MaxTypeAlignStr += A->getValue();
7428       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7429     }
7430   } else if (RawTriple.isOSDarwin()) {
7431     if (!SkipMaxTypeAlign) {
7432       std::string MaxTypeAlignStr = "-fmax-type-align=16";
7433       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7434     }
7435   }
7436 
7437   if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
7438     CmdArgs.push_back("-Qn");
7439 
7440   // -fno-common is the default, set -fcommon only when that flag is set.
7441   Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
7442 
7443   // -fsigned-bitfields is default, and clang doesn't yet support
7444   // -funsigned-bitfields.
7445   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
7446                     options::OPT_funsigned_bitfields, true))
7447     D.Diag(diag::warn_drv_clang_unsupported)
7448         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
7449 
7450   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7451   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
7452     D.Diag(diag::err_drv_clang_unsupported)
7453         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
7454 
7455   // -finput_charset=UTF-8 is default. Reject others
7456   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
7457     StringRef value = inputCharset->getValue();
7458     if (!value.equals_insensitive("utf-8"))
7459       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
7460                                           << value;
7461   }
7462 
7463   // -fexec_charset=UTF-8 is default. Reject others
7464   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
7465     StringRef value = execCharset->getValue();
7466     if (!value.equals_insensitive("utf-8"))
7467       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
7468                                           << value;
7469   }
7470 
7471   RenderDiagnosticsOptions(D, Args, CmdArgs);
7472 
7473   Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
7474                     options::OPT_fno_asm_blocks);
7475 
7476   Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
7477                      options::OPT_fno_gnu_inline_asm);
7478 
7479   handleVectorizeLoopsArgs(Args, CmdArgs);
7480   handleVectorizeSLPArgs(Args, CmdArgs);
7481 
7482   StringRef VecWidth = parseMPreferVectorWidthOption(D.getDiags(), Args);
7483   if (!VecWidth.empty())
7484     CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + VecWidth));
7485 
7486   Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
7487   Args.AddLastArg(CmdArgs,
7488                   options::OPT_fsanitize_undefined_strip_path_components_EQ);
7489 
7490   // -fdollars-in-identifiers default varies depending on platform and
7491   // language; only pass if specified.
7492   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
7493                                options::OPT_fno_dollars_in_identifiers)) {
7494     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
7495       CmdArgs.push_back("-fdollars-in-identifiers");
7496     else
7497       CmdArgs.push_back("-fno-dollars-in-identifiers");
7498   }
7499 
7500   Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
7501                     options::OPT_fno_apple_pragma_pack);
7502 
7503   // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7504   if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7505     renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
7506 
7507   bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
7508                                      options::OPT_fno_rewrite_imports, false);
7509   if (RewriteImports)
7510     CmdArgs.push_back("-frewrite-imports");
7511 
7512   Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
7513                     options::OPT_fno_directives_only);
7514 
7515   // Enable rewrite includes if the user's asked for it or if we're generating
7516   // diagnostics.
7517   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
7518   // nice to enable this when doing a crashdump for modules as well.
7519   if (Args.hasFlag(options::OPT_frewrite_includes,
7520                    options::OPT_fno_rewrite_includes, false) ||
7521       (C.isForDiagnostics() && !HaveModules))
7522     CmdArgs.push_back("-frewrite-includes");
7523 
7524   if (Args.hasFlag(options::OPT_fzos_extensions,
7525                    options::OPT_fno_zos_extensions, false))
7526     CmdArgs.push_back("-fzos-extensions");
7527   else if (Args.hasArg(options::OPT_fno_zos_extensions))
7528     CmdArgs.push_back("-fno-zos-extensions");
7529 
7530   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
7531   if (Arg *A = Args.getLastArg(options::OPT_traditional,
7532                                options::OPT_traditional_cpp)) {
7533     if (isa<PreprocessJobAction>(JA))
7534       CmdArgs.push_back("-traditional-cpp");
7535     else
7536       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
7537   }
7538 
7539   Args.AddLastArg(CmdArgs, options::OPT_dM);
7540   Args.AddLastArg(CmdArgs, options::OPT_dD);
7541   Args.AddLastArg(CmdArgs, options::OPT_dI);
7542 
7543   Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
7544 
7545   // Handle serialized diagnostics.
7546   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
7547     CmdArgs.push_back("-serialize-diagnostic-file");
7548     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
7549   }
7550 
7551   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
7552     CmdArgs.push_back("-fretain-comments-from-system-headers");
7553 
7554   if (Arg *A = Args.getLastArg(options::OPT_fextend_variable_liveness_EQ)) {
7555     A->render(Args, CmdArgs);
7556   } else if (Arg *A = Args.getLastArg(options::OPT_O_Group);
7557              A && A->containsValue("g")) {
7558     // Set -fextend-variable-liveness=all by default at -Og.
7559     CmdArgs.push_back("-fextend-variable-liveness=all");
7560   }
7561 
7562   // Forward -fcomment-block-commands to -cc1.
7563   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
7564   // Forward -fparse-all-comments to -cc1.
7565   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
7566 
7567   // Turn -fplugin=name.so into -load name.so
7568   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
7569     CmdArgs.push_back("-load");
7570     CmdArgs.push_back(A->getValue());
7571     A->claim();
7572   }
7573 
7574   // Turn -fplugin-arg-pluginname-key=value into
7575   // -plugin-arg-pluginname key=value
7576   // GCC has an actual plugin_argument struct with key/value pairs that it
7577   // passes to its plugins, but we don't, so just pass it on as-is.
7578   //
7579   // The syntax for -fplugin-arg- is ambiguous if both plugin name and
7580   // argument key are allowed to contain dashes. GCC therefore only
7581   // allows dashes in the key. We do the same.
7582   for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
7583     auto ArgValue = StringRef(A->getValue());
7584     auto FirstDashIndex = ArgValue.find('-');
7585     StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
7586     StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
7587 
7588     A->claim();
7589     if (FirstDashIndex == StringRef::npos || Arg.empty()) {
7590       if (PluginName.empty()) {
7591         D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
7592       } else {
7593         D.Diag(diag::warn_drv_missing_plugin_arg)
7594             << PluginName << A->getAsString(Args);
7595       }
7596       continue;
7597     }
7598 
7599     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
7600     CmdArgs.push_back(Args.MakeArgString(Arg));
7601   }
7602 
7603   // Forward -fpass-plugin=name.so to -cc1.
7604   for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
7605     CmdArgs.push_back(
7606         Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
7607     A->claim();
7608   }
7609 
7610   // Forward --vfsoverlay to -cc1.
7611   for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
7612     CmdArgs.push_back("--vfsoverlay");
7613     CmdArgs.push_back(A->getValue());
7614     A->claim();
7615   }
7616 
7617   Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
7618                     options::OPT_fno_safe_buffer_usage_suggestions);
7619 
7620   Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,
7621                     options::OPT_fno_experimental_late_parse_attributes);
7622 
7623   if (Args.hasFlag(options::OPT_funique_source_file_names,
7624                    options::OPT_fno_unique_source_file_names, false)) {
7625     if (Arg *A = Args.getLastArg(options::OPT_unique_source_file_identifier_EQ))
7626       A->render(Args, CmdArgs);
7627     else
7628       CmdArgs.push_back(Args.MakeArgString(
7629           Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
7630   }
7631 
7632   // Setup statistics file output.
7633   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
7634   if (!StatsFile.empty()) {
7635     CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
7636     if (D.CCPrintInternalStats)
7637       CmdArgs.push_back("-stats-file-append");
7638   }
7639 
7640   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
7641   // parser.
7642   for (auto Arg : Args.filtered(options::OPT_Xclang)) {
7643     Arg->claim();
7644     // -finclude-default-header flag is for preprocessor,
7645     // do not pass it to other cc1 commands when save-temps is enabled
7646     if (C.getDriver().isSaveTempsEnabled() &&
7647         !isa<PreprocessJobAction>(JA)) {
7648       if (StringRef(Arg->getValue()) == "-finclude-default-header")
7649         continue;
7650     }
7651     CmdArgs.push_back(Arg->getValue());
7652   }
7653   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
7654     A->claim();
7655 
7656     // We translate this by hand to the -cc1 argument, since nightly test uses
7657     // it and developers have been trained to spell it with -mllvm. Both
7658     // spellings are now deprecated and should be removed.
7659     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
7660       CmdArgs.push_back("-disable-llvm-optzns");
7661     } else {
7662       A->render(Args, CmdArgs);
7663     }
7664   }
7665 
7666   // This needs to run after -Xclang argument forwarding to pick up the target
7667   // features enabled through -Xclang -target-feature flags.
7668   SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
7669 
7670 #if CLANG_ENABLE_CIR
7671   // Forward -mmlir arguments to to the MLIR option parser.
7672   for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
7673     A->claim();
7674     A->render(Args, CmdArgs);
7675   }
7676 #endif // CLANG_ENABLE_CIR
7677 
7678   // With -save-temps, we want to save the unoptimized bitcode output from the
7679   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
7680   // by the frontend.
7681   // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
7682   // has slightly different breakdown between stages.
7683   // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
7684   // pristine IR generated by the frontend. Ideally, a new compile action should
7685   // be added so both IR can be captured.
7686   if ((C.getDriver().isSaveTempsEnabled() ||
7687        JA.isHostOffloading(Action::OFK_OpenMP)) &&
7688       !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
7689       isa<CompileJobAction>(JA))
7690     CmdArgs.push_back("-disable-llvm-passes");
7691 
7692   Args.AddAllArgs(CmdArgs, options::OPT_undef);
7693 
7694   const char *Exec = D.getClangProgramPath();
7695 
7696   // Optionally embed the -cc1 level arguments into the debug info or a
7697   // section, for build analysis.
7698   // Also record command line arguments into the debug info if
7699   // -grecord-gcc-switches options is set on.
7700   // By default, -gno-record-gcc-switches is set on and no recording.
7701   auto GRecordSwitches = false;
7702   auto FRecordSwitches = false;
7703   if (shouldRecordCommandLine(TC, Args, FRecordSwitches, GRecordSwitches)) {
7704     auto FlagsArgString = renderEscapedCommandLine(TC, Args);
7705     if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
7706       CmdArgs.push_back("-dwarf-debug-flags");
7707       CmdArgs.push_back(FlagsArgString);
7708     }
7709     if (FRecordSwitches) {
7710       CmdArgs.push_back("-record-command-line");
7711       CmdArgs.push_back(FlagsArgString);
7712     }
7713   }
7714 
7715   // Host-side offloading compilation receives all device-side outputs. Include
7716   // them in the host compilation depending on the target. If the host inputs
7717   // are not empty we use the new-driver scheme, otherwise use the old scheme.
7718   if ((IsCuda || IsHIP) && CudaDeviceInput) {
7719     CmdArgs.push_back("-fcuda-include-gpubinary");
7720     CmdArgs.push_back(CudaDeviceInput->getFilename());
7721   } else if (!HostOffloadingInputs.empty()) {
7722     if (IsCuda && !IsRDCMode) {
7723       assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7724       CmdArgs.push_back("-fcuda-include-gpubinary");
7725       CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
7726     } else {
7727       for (const InputInfo Input : HostOffloadingInputs)
7728         CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
7729                                              TC.getInputFilename(Input)));
7730     }
7731   }
7732 
7733   if (IsCuda) {
7734     if (Args.hasFlag(options::OPT_fcuda_short_ptr,
7735                      options::OPT_fno_cuda_short_ptr, false))
7736       CmdArgs.push_back("-fcuda-short-ptr");
7737   }
7738 
7739   if (IsCuda || IsHIP) {
7740     // Determine the original source input.
7741     const Action *SourceAction = &JA;
7742     while (SourceAction->getKind() != Action::InputClass) {
7743       assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7744       SourceAction = SourceAction->getInputs()[0];
7745     }
7746     auto CUID = cast<InputAction>(SourceAction)->getId();
7747     if (!CUID.empty())
7748       CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
7749 
7750     // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
7751     // be overriden by -fno-gpu-approx-transcendentals.
7752     bool UseApproxTranscendentals = Args.hasFlag(
7753         options::OPT_ffast_math, options::OPT_fno_fast_math, false);
7754     if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
7755                      options::OPT_fno_gpu_approx_transcendentals,
7756                      UseApproxTranscendentals))
7757       CmdArgs.push_back("-fgpu-approx-transcendentals");
7758   } else {
7759     Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
7760                       options::OPT_fno_gpu_approx_transcendentals);
7761   }
7762 
7763   if (IsHIP) {
7764     CmdArgs.push_back("-fcuda-allow-variadic-functions");
7765     Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
7766   }
7767 
7768   Args.AddAllArgs(CmdArgs,
7769                   options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
7770 
7771   Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
7772                   options::OPT_fno_offload_uniform_block);
7773 
7774   Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
7775                   options::OPT_fno_offload_implicit_host_device_templates);
7776 
7777   if (IsCudaDevice || IsHIPDevice) {
7778     StringRef InlineThresh =
7779         Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
7780     if (!InlineThresh.empty()) {
7781       std::string ArgStr =
7782           std::string("-inline-threshold=") + InlineThresh.str();
7783       CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
7784     }
7785   }
7786 
7787   if (IsHIPDevice)
7788     Args.addOptOutFlag(CmdArgs,
7789                        options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
7790                        options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
7791 
7792   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
7793   // to specify the result of the compile phase on the host, so the meaningful
7794   // device declarations can be identified. Also, -fopenmp-is-target-device is
7795   // passed along to tell the frontend that it is generating code for a device,
7796   // so that only the relevant declarations are emitted.
7797   if (IsOpenMPDevice) {
7798     CmdArgs.push_back("-fopenmp-is-target-device");
7799     // If we are offloading cuda/hip via llvm, it's also "cuda device code".
7800     if (Args.hasArg(options::OPT_foffload_via_llvm))
7801       CmdArgs.push_back("-fcuda-is-device");
7802 
7803     if (OpenMPDeviceInput) {
7804       CmdArgs.push_back("-fopenmp-host-ir-file-path");
7805       CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
7806     }
7807   }
7808 
7809   if (Triple.isAMDGPU()) {
7810     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7811 
7812     Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
7813                       options::OPT_mno_unsafe_fp_atomics);
7814     Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
7815                        options::OPT_mno_amdgpu_ieee);
7816   }
7817 
7818   addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
7819 
7820   bool VirtualFunctionElimination =
7821       Args.hasFlag(options::OPT_fvirtual_function_elimination,
7822                    options::OPT_fno_virtual_function_elimination, false);
7823   if (VirtualFunctionElimination) {
7824     // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7825     // in the future).
7826     if (LTOMode != LTOK_Full)
7827       D.Diag(diag::err_drv_argument_only_allowed_with)
7828           << "-fvirtual-function-elimination"
7829           << "-flto=full";
7830 
7831     CmdArgs.push_back("-fvirtual-function-elimination");
7832   }
7833 
7834   // VFE requires whole-program-vtables, and enables it by default.
7835   bool WholeProgramVTables = Args.hasFlag(
7836       options::OPT_fwhole_program_vtables,
7837       options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
7838   if (VirtualFunctionElimination && !WholeProgramVTables) {
7839     D.Diag(diag::err_drv_argument_not_allowed_with)
7840         << "-fno-whole-program-vtables"
7841         << "-fvirtual-function-elimination";
7842   }
7843 
7844   if (WholeProgramVTables) {
7845     // PS4 uses the legacy LTO API, which does not support this feature in
7846     // ThinLTO mode.
7847     bool IsPS4 = getToolChain().getTriple().isPS4();
7848 
7849     // Check if we passed LTO options but they were suppressed because this is a
7850     // device offloading action, or we passed device offload LTO options which
7851     // were suppressed because this is not the device offload action.
7852     // Check if we are using PS4 in regular LTO mode.
7853     // Otherwise, issue an error.
7854 
7855     auto OtherLTOMode =
7856         IsDeviceOffloadAction ? D.getLTOMode() : D.getOffloadLTOMode();
7857     auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
7858 
7859     if ((!IsUsingLTO && !OtherIsUsingLTO) ||
7860         (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
7861       D.Diag(diag::err_drv_argument_only_allowed_with)
7862           << "-fwhole-program-vtables"
7863           << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
7864 
7865     // Propagate -fwhole-program-vtables if this is an LTO compile.
7866     if (IsUsingLTO)
7867       CmdArgs.push_back("-fwhole-program-vtables");
7868   }
7869 
7870   bool DefaultsSplitLTOUnit =
7871       ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
7872           (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
7873       (!Triple.isPS4() && UnifiedLTO);
7874   bool SplitLTOUnit =
7875       Args.hasFlag(options::OPT_fsplit_lto_unit,
7876                    options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
7877   if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7878     D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7879                                                     << "-fsanitize=cfi";
7880   if (SplitLTOUnit)
7881     CmdArgs.push_back("-fsplit-lto-unit");
7882 
7883   if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
7884                                options::OPT_fno_fat_lto_objects)) {
7885     if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
7886       assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
7887       if (!Triple.isOSBinFormatELF()) {
7888         D.Diag(diag::err_drv_unsupported_opt_for_target)
7889             << A->getAsString(Args) << TC.getTripleString();
7890       }
7891       CmdArgs.push_back(Args.MakeArgString(
7892           Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
7893       CmdArgs.push_back("-flto-unit");
7894       CmdArgs.push_back("-ffat-lto-objects");
7895       A->render(Args, CmdArgs);
7896     }
7897   }
7898 
7899   if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
7900                                options::OPT_fno_global_isel)) {
7901     CmdArgs.push_back("-mllvm");
7902     if (A->getOption().matches(options::OPT_fglobal_isel)) {
7903       CmdArgs.push_back("-global-isel=1");
7904 
7905       // GISel is on by default on AArch64 -O0, so don't bother adding
7906       // the fallback remarks for it. Other combinations will add a warning of
7907       // some kind.
7908       bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
7909       bool IsOptLevelSupported = false;
7910 
7911       Arg *A = Args.getLastArg(options::OPT_O_Group);
7912       if (Triple.getArch() == llvm::Triple::aarch64) {
7913         if (!A || A->getOption().matches(options::OPT_O0))
7914           IsOptLevelSupported = true;
7915       }
7916       if (!IsArchSupported || !IsOptLevelSupported) {
7917         CmdArgs.push_back("-mllvm");
7918         CmdArgs.push_back("-global-isel-abort=2");
7919 
7920         if (!IsArchSupported)
7921           D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
7922         else
7923           D.Diag(diag::warn_drv_global_isel_incomplete_opt);
7924       }
7925     } else {
7926       CmdArgs.push_back("-global-isel=0");
7927     }
7928   }
7929 
7930   if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
7931                                options::OPT_fno_force_enable_int128)) {
7932     if (A->getOption().matches(options::OPT_fforce_enable_int128))
7933       CmdArgs.push_back("-fforce-enable-int128");
7934   }
7935 
7936   Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
7937                     options::OPT_fno_keep_static_consts);
7938   Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
7939                     options::OPT_fno_keep_persistent_storage_variables);
7940   Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
7941                     options::OPT_fno_complete_member_pointers);
7942   if (Arg *A = Args.getLastArg(options::OPT_cxx_static_destructors_EQ))
7943     A->render(Args, CmdArgs);
7944 
7945   addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
7946 
7947   addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
7948 
7949   if (Triple.isAArch64() &&
7950       (Args.hasArg(options::OPT_mno_fmv) ||
7951        (Triple.isAndroid() && Triple.isAndroidVersionLT(23)) ||
7952        getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
7953     // Disable Function Multiversioning on AArch64 target.
7954     CmdArgs.push_back("-target-feature");
7955     CmdArgs.push_back("-fmv");
7956   }
7957 
7958   if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
7959                    (TC.getTriple().isOSBinFormatELF() ||
7960                     TC.getTriple().isOSBinFormatCOFF()) &&
7961                        !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
7962                        !TC.getTriple().isOSNetBSD() &&
7963                        !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
7964                        !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
7965     CmdArgs.push_back("-faddrsig");
7966 
7967   if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
7968       (EH || UnwindTables || AsyncUnwindTables ||
7969        DebugInfoKind != llvm::codegenoptions::NoDebugInfo))
7970     CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
7971 
7972   if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
7973     std::string Str = A->getAsString(Args);
7974     if (!TC.getTriple().isOSBinFormatELF())
7975       D.Diag(diag::err_drv_unsupported_opt_for_target)
7976           << Str << TC.getTripleString();
7977     CmdArgs.push_back(Args.MakeArgString(Str));
7978   }
7979 
7980   // Add the "-o out -x type src.c" flags last. This is done primarily to make
7981   // the -cc1 command easier to edit when reproducing compiler crashes.
7982   if (Output.getType() == types::TY_Dependencies) {
7983     // Handled with other dependency code.
7984   } else if (Output.isFilename()) {
7985     if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
7986         Output.getType() == clang::driver::types::TY_IFS) {
7987       SmallString<128> OutputFilename(Output.getFilename());
7988       llvm::sys::path::replace_extension(OutputFilename, "ifs");
7989       CmdArgs.push_back("-o");
7990       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7991     } else {
7992       CmdArgs.push_back("-o");
7993       CmdArgs.push_back(Output.getFilename());
7994     }
7995   } else {
7996     assert(Output.isNothing() && "Invalid output.");
7997   }
7998 
7999   addDashXForInput(Args, Input, CmdArgs);
8000 
8001   ArrayRef<InputInfo> FrontendInputs = Input;
8002   if (IsExtractAPI)
8003     FrontendInputs = ExtractAPIInputs;
8004   else if (Input.isNothing())
8005     FrontendInputs = {};
8006 
8007   for (const InputInfo &Input : FrontendInputs) {
8008     if (Input.isFilename())
8009       CmdArgs.push_back(Input.getFilename());
8010     else
8011       Input.getInputArg().renderAsInput(Args, CmdArgs);
8012   }
8013 
8014   if (D.CC1Main && !D.CCGenDiagnostics) {
8015     // Invoke the CC1 directly in this process
8016     C.addCommand(std::make_unique<CC1Command>(
8017         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8018         Output, D.getPrependArg()));
8019   } else {
8020     C.addCommand(std::make_unique<Command>(
8021         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8022         Output, D.getPrependArg()));
8023   }
8024 
8025   // Make the compile command echo its inputs for /showFilenames.
8026   if (Output.getType() == types::TY_Object &&
8027       Args.hasFlag(options::OPT__SLASH_showFilenames,
8028                    options::OPT__SLASH_showFilenames_, false)) {
8029     C.getJobs().getJobs().back()->PrintInputFilenames = true;
8030   }
8031 
8032   if (Arg *A = Args.getLastArg(options::OPT_pg))
8033     if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8034         !Args.hasArg(options::OPT_mfentry))
8035       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8036                                                       << A->getAsString(Args);
8037 
8038   // Claim some arguments which clang supports automatically.
8039 
8040   // -fpch-preprocess is used with gcc to add a special marker in the output to
8041   // include the PCH file.
8042   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
8043 
8044   // Claim some arguments which clang doesn't support, but we don't
8045   // care to warn the user about.
8046   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
8047   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
8048 
8049   // Disable warnings for clang -E -emit-llvm foo.c
8050   Args.ClaimAllArgs(options::OPT_emit_llvm);
8051 }
8052 
Clang(const ToolChain & TC,bool HasIntegratedBackend)8053 Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8054     // CAUTION! The first constructor argument ("clang") is not arbitrary,
8055     // as it is for other tools. Some operations on a Tool actually test
8056     // whether that tool is Clang based on the Tool's Name as a string.
8057     : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8058 
~Clang()8059 Clang::~Clang() {}
8060 
8061 /// Add options related to the Objective-C runtime/ABI.
8062 ///
8063 /// Returns true if the runtime is non-fragile.
AddObjCRuntimeArgs(const ArgList & args,const InputInfoList & inputs,ArgStringList & cmdArgs,RewriteKind rewriteKind) const8064 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8065                                       const InputInfoList &inputs,
8066                                       ArgStringList &cmdArgs,
8067                                       RewriteKind rewriteKind) const {
8068   // Look for the controlling runtime option.
8069   Arg *runtimeArg =
8070       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
8071                       options::OPT_fobjc_runtime_EQ);
8072 
8073   // Just forward -fobjc-runtime= to the frontend.  This supercedes
8074   // options about fragility.
8075   if (runtimeArg &&
8076       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
8077     ObjCRuntime runtime;
8078     StringRef value = runtimeArg->getValue();
8079     if (runtime.tryParse(value)) {
8080       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
8081           << value;
8082     }
8083     if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8084         (runtime.getVersion() >= VersionTuple(2, 0)))
8085       if (!getToolChain().getTriple().isOSBinFormatELF() &&
8086           !getToolChain().getTriple().isOSBinFormatCOFF()) {
8087         getToolChain().getDriver().Diag(
8088             diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8089           << runtime.getVersion().getMajor();
8090       }
8091 
8092     runtimeArg->render(args, cmdArgs);
8093     return runtime;
8094   }
8095 
8096   // Otherwise, we'll need the ABI "version".  Version numbers are
8097   // slightly confusing for historical reasons:
8098   //   1 - Traditional "fragile" ABI
8099   //   2 - Non-fragile ABI, version 1
8100   //   3 - Non-fragile ABI, version 2
8101   unsigned objcABIVersion = 1;
8102   // If -fobjc-abi-version= is present, use that to set the version.
8103   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
8104     StringRef value = abiArg->getValue();
8105     if (value == "1")
8106       objcABIVersion = 1;
8107     else if (value == "2")
8108       objcABIVersion = 2;
8109     else if (value == "3")
8110       objcABIVersion = 3;
8111     else
8112       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
8113   } else {
8114     // Otherwise, determine if we are using the non-fragile ABI.
8115     bool nonFragileABIIsDefault =
8116         (rewriteKind == RK_NonFragile ||
8117          (rewriteKind == RK_None &&
8118           getToolChain().IsObjCNonFragileABIDefault()));
8119     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
8120                      options::OPT_fno_objc_nonfragile_abi,
8121                      nonFragileABIIsDefault)) {
8122 // Determine the non-fragile ABI version to use.
8123 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8124       unsigned nonFragileABIVersion = 1;
8125 #else
8126       unsigned nonFragileABIVersion = 2;
8127 #endif
8128 
8129       if (Arg *abiArg =
8130               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8131         StringRef value = abiArg->getValue();
8132         if (value == "1")
8133           nonFragileABIVersion = 1;
8134         else if (value == "2")
8135           nonFragileABIVersion = 2;
8136         else
8137           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
8138               << value;
8139       }
8140 
8141       objcABIVersion = 1 + nonFragileABIVersion;
8142     } else {
8143       objcABIVersion = 1;
8144     }
8145   }
8146 
8147   // We don't actually care about the ABI version other than whether
8148   // it's non-fragile.
8149   bool isNonFragile = objcABIVersion != 1;
8150 
8151   // If we have no runtime argument, ask the toolchain for its default runtime.
8152   // However, the rewriter only really supports the Mac runtime, so assume that.
8153   ObjCRuntime runtime;
8154   if (!runtimeArg) {
8155     switch (rewriteKind) {
8156     case RK_None:
8157       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8158       break;
8159     case RK_Fragile:
8160       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8161       break;
8162     case RK_NonFragile:
8163       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8164       break;
8165     }
8166 
8167     // -fnext-runtime
8168   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
8169     // On Darwin, make this use the default behavior for the toolchain.
8170     if (getToolChain().getTriple().isOSDarwin()) {
8171       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8172 
8173       // Otherwise, build for a generic macosx port.
8174     } else {
8175       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8176     }
8177 
8178     // -fgnu-runtime
8179   } else {
8180     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8181     // Legacy behaviour is to target the gnustep runtime if we are in
8182     // non-fragile mode or the GCC runtime in fragile mode.
8183     if (isNonFragile)
8184       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8185     else
8186       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8187   }
8188 
8189   if (llvm::any_of(inputs, [](const InputInfo &input) {
8190         return types::isObjC(input.getType());
8191       }))
8192     cmdArgs.push_back(
8193         args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
8194   return runtime;
8195 }
8196 
maybeConsumeDash(const std::string & EH,size_t & I)8197 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8198   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8199   I += HaveDash;
8200   return !HaveDash;
8201 }
8202 
8203 namespace {
8204 struct EHFlags {
8205   bool Synch = false;
8206   bool Asynch = false;
8207   bool NoUnwindC = false;
8208 };
8209 } // end anonymous namespace
8210 
8211 /// /EH controls whether to run destructor cleanups when exceptions are
8212 /// thrown.  There are three modifiers:
8213 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8214 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8215 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8216 /// - c: Assume that extern "C" functions are implicitly nounwind.
8217 /// The default is /EHs-c-, meaning cleanups are disabled.
parseClangCLEHFlags(const Driver & D,const ArgList & Args,bool isWindowsMSVC)8218 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8219                                    bool isWindowsMSVC) {
8220   EHFlags EH;
8221 
8222   std::vector<std::string> EHArgs =
8223       Args.getAllArgValues(options::OPT__SLASH_EH);
8224   for (const auto &EHVal : EHArgs) {
8225     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8226       switch (EHVal[I]) {
8227       case 'a':
8228         EH.Asynch = maybeConsumeDash(EHVal, I);
8229         if (EH.Asynch) {
8230           // Async exceptions are Windows MSVC only.
8231           if (!isWindowsMSVC) {
8232             EH.Asynch = false;
8233             D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8234             continue;
8235           }
8236           EH.Synch = false;
8237         }
8238         continue;
8239       case 'c':
8240         EH.NoUnwindC = maybeConsumeDash(EHVal, I);
8241         continue;
8242       case 's':
8243         EH.Synch = maybeConsumeDash(EHVal, I);
8244         if (EH.Synch)
8245           EH.Asynch = false;
8246         continue;
8247       default:
8248         break;
8249       }
8250       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8251       break;
8252     }
8253   }
8254   // The /GX, /GX- flags are only processed if there are not /EH flags.
8255   // The default is that /GX is not specified.
8256   if (EHArgs.empty() &&
8257       Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
8258                    /*Default=*/false)) {
8259     EH.Synch = true;
8260     EH.NoUnwindC = true;
8261   }
8262 
8263   if (Args.hasArg(options::OPT__SLASH_kernel)) {
8264     EH.Synch = false;
8265     EH.NoUnwindC = false;
8266     EH.Asynch = false;
8267   }
8268 
8269   return EH;
8270 }
8271 
AddClangCLArgs(const ArgList & Args,types::ID InputType,ArgStringList & CmdArgs) const8272 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8273                            ArgStringList &CmdArgs) const {
8274   bool isNVPTX = getToolChain().getTriple().isNVPTX();
8275 
8276   ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
8277 
8278   if (Arg *ShowIncludes =
8279           Args.getLastArg(options::OPT__SLASH_showIncludes,
8280                           options::OPT__SLASH_showIncludes_user)) {
8281     CmdArgs.push_back("--show-includes");
8282     if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
8283       CmdArgs.push_back("-sys-header-deps");
8284   }
8285 
8286   // This controls whether or not we emit RTTI data for polymorphic types.
8287   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8288                    /*Default=*/false))
8289     CmdArgs.push_back("-fno-rtti-data");
8290 
8291   // This controls whether or not we emit stack-protector instrumentation.
8292   // In MSVC, Buffer Security Check (/GS) is on by default.
8293   if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
8294                                /*Default=*/true)) {
8295     CmdArgs.push_back("-stack-protector");
8296     CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
8297   }
8298 
8299   const Driver &D = getToolChain().getDriver();
8300 
8301   bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8302   EHFlags EH = parseClangCLEHFlags(D, Args, IsWindowsMSVC);
8303   if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8304     if (types::isCXX(InputType))
8305       CmdArgs.push_back("-fcxx-exceptions");
8306     CmdArgs.push_back("-fexceptions");
8307     if (EH.Asynch)
8308       CmdArgs.push_back("-fasync-exceptions");
8309   }
8310   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
8311     CmdArgs.push_back("-fexternc-nounwind");
8312 
8313   // /EP should expand to -E -P.
8314   if (Args.hasArg(options::OPT__SLASH_EP)) {
8315     CmdArgs.push_back("-E");
8316     CmdArgs.push_back("-P");
8317   }
8318 
8319  if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
8320                   options::OPT__SLASH_Zc_dllexportInlines,
8321                   false)) {
8322   CmdArgs.push_back("-fno-dllexport-inlines");
8323  }
8324 
8325  if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
8326                   options::OPT__SLASH_Zc_wchar_t, false)) {
8327    CmdArgs.push_back("-fno-wchar");
8328  }
8329 
8330  if (Args.hasArg(options::OPT__SLASH_kernel)) {
8331    llvm::Triple::ArchType Arch = getToolChain().getArch();
8332    std::vector<std::string> Values =
8333        Args.getAllArgValues(options::OPT__SLASH_arch);
8334    if (!Values.empty()) {
8335      llvm::SmallSet<std::string, 4> SupportedArches;
8336      if (Arch == llvm::Triple::x86)
8337        SupportedArches.insert("IA32");
8338 
8339      for (auto &V : Values)
8340        if (!SupportedArches.contains(V))
8341          D.Diag(diag::err_drv_argument_not_allowed_with)
8342              << std::string("/arch:").append(V) << "/kernel";
8343    }
8344 
8345    CmdArgs.push_back("-fno-rtti");
8346    if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
8347      D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
8348                                                      << "/kernel";
8349  }
8350 
8351   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
8352   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
8353   if (MostGeneralArg && BestCaseArg)
8354     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8355         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8356 
8357   if (MostGeneralArg) {
8358     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
8359     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
8360     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
8361 
8362     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8363     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8364     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8365       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8366           << FirstConflict->getAsString(Args)
8367           << SecondConflict->getAsString(Args);
8368 
8369     if (SingleArg)
8370       CmdArgs.push_back("-fms-memptr-rep=single");
8371     else if (MultipleArg)
8372       CmdArgs.push_back("-fms-memptr-rep=multiple");
8373     else
8374       CmdArgs.push_back("-fms-memptr-rep=virtual");
8375   }
8376 
8377   if (Args.hasArg(options::OPT_regcall4))
8378     CmdArgs.push_back("-regcall4");
8379 
8380   // Parse the default calling convention options.
8381   if (Arg *CCArg =
8382           Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
8383                           options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
8384                           options::OPT__SLASH_Gregcall)) {
8385     unsigned DCCOptId = CCArg->getOption().getID();
8386     const char *DCCFlag = nullptr;
8387     bool ArchSupported = !isNVPTX;
8388     llvm::Triple::ArchType Arch = getToolChain().getArch();
8389     switch (DCCOptId) {
8390     case options::OPT__SLASH_Gd:
8391       DCCFlag = "-fdefault-calling-conv=cdecl";
8392       break;
8393     case options::OPT__SLASH_Gr:
8394       ArchSupported = Arch == llvm::Triple::x86;
8395       DCCFlag = "-fdefault-calling-conv=fastcall";
8396       break;
8397     case options::OPT__SLASH_Gz:
8398       ArchSupported = Arch == llvm::Triple::x86;
8399       DCCFlag = "-fdefault-calling-conv=stdcall";
8400       break;
8401     case options::OPT__SLASH_Gv:
8402       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8403       DCCFlag = "-fdefault-calling-conv=vectorcall";
8404       break;
8405     case options::OPT__SLASH_Gregcall:
8406       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8407       DCCFlag = "-fdefault-calling-conv=regcall";
8408       break;
8409     }
8410 
8411     // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
8412     if (ArchSupported && DCCFlag)
8413       CmdArgs.push_back(DCCFlag);
8414   }
8415 
8416   if (Args.hasArg(options::OPT__SLASH_Gregcall4))
8417     CmdArgs.push_back("-regcall4");
8418 
8419   Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
8420 
8421   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
8422     CmdArgs.push_back("-fdiagnostics-format");
8423     CmdArgs.push_back("msvc");
8424   }
8425 
8426   if (Args.hasArg(options::OPT__SLASH_kernel))
8427     CmdArgs.push_back("-fms-kernel");
8428 
8429   // Unwind v2 (epilog) information for x64 Windows.
8430   if (Args.hasArg(options::OPT__SLASH_d2epilogunwindrequirev2))
8431     CmdArgs.push_back("-fwinx64-eh-unwindv2=required");
8432   else if (Args.hasArg(options::OPT__SLASH_d2epilogunwind))
8433     CmdArgs.push_back("-fwinx64-eh-unwindv2=best-effort");
8434 
8435   for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
8436     StringRef GuardArgs = A->getValue();
8437     // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8438     // "ehcont-".
8439     if (GuardArgs.equals_insensitive("cf")) {
8440       // Emit CFG instrumentation and the table of address-taken functions.
8441       CmdArgs.push_back("-cfguard");
8442     } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
8443       // Emit only the table of address-taken functions.
8444       CmdArgs.push_back("-cfguard-no-checks");
8445     } else if (GuardArgs.equals_insensitive("ehcont")) {
8446       // Emit EH continuation table.
8447       CmdArgs.push_back("-ehcontguard");
8448     } else if (GuardArgs.equals_insensitive("cf-") ||
8449                GuardArgs.equals_insensitive("ehcont-")) {
8450       // Do nothing, but we might want to emit a security warning in future.
8451     } else {
8452       D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8453     }
8454     A->claim();
8455   }
8456 
8457   for (const auto &FuncOverride :
8458        Args.getAllArgValues(options::OPT__SLASH_funcoverride)) {
8459     CmdArgs.push_back(Args.MakeArgString(
8460         Twine("-loader-replaceable-function=") + FuncOverride));
8461   }
8462 }
8463 
getBaseInputName(const ArgList & Args,const InputInfo & Input)8464 const char *Clang::getBaseInputName(const ArgList &Args,
8465                                     const InputInfo &Input) {
8466   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
8467 }
8468 
getBaseInputStem(const ArgList & Args,const InputInfoList & Inputs)8469 const char *Clang::getBaseInputStem(const ArgList &Args,
8470                                     const InputInfoList &Inputs) {
8471   const char *Str = getBaseInputName(Args, Inputs[0]);
8472 
8473   if (const char *End = strrchr(Str, '.'))
8474     return Args.MakeArgString(std::string(Str, End));
8475 
8476   return Str;
8477 }
8478 
getDependencyFileName(const ArgList & Args,const InputInfoList & Inputs)8479 const char *Clang::getDependencyFileName(const ArgList &Args,
8480                                          const InputInfoList &Inputs) {
8481   // FIXME: Think about this more.
8482 
8483   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
8484     SmallString<128> OutputFilename(OutputOpt->getValue());
8485     llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
8486     return Args.MakeArgString(OutputFilename);
8487   }
8488 
8489   return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
8490 }
8491 
8492 // Begin ClangAs
8493 
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const8494 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
8495                                 ArgStringList &CmdArgs) const {
8496   StringRef CPUName;
8497   StringRef ABIName;
8498   const llvm::Triple &Triple = getToolChain().getTriple();
8499   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
8500 
8501   CmdArgs.push_back("-target-abi");
8502   CmdArgs.push_back(ABIName.data());
8503 }
8504 
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const8505 void ClangAs::AddX86TargetArgs(const ArgList &Args,
8506                                ArgStringList &CmdArgs) const {
8507   addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
8508                         /*IsLTO=*/false);
8509 
8510   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
8511     StringRef Value = A->getValue();
8512     if (Value == "intel" || Value == "att") {
8513       CmdArgs.push_back("-mllvm");
8514       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
8515     } else {
8516       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
8517           << A->getSpelling() << Value;
8518     }
8519   }
8520 }
8521 
AddLoongArchTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const8522 void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
8523                                      ArgStringList &CmdArgs) const {
8524   CmdArgs.push_back("-target-abi");
8525   CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
8526                                                getToolChain().getTriple())
8527                         .data());
8528 }
8529 
AddRISCVTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const8530 void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
8531                                ArgStringList &CmdArgs) const {
8532   const llvm::Triple &Triple = getToolChain().getTriple();
8533   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
8534 
8535   CmdArgs.push_back("-target-abi");
8536   CmdArgs.push_back(ABIName.data());
8537 
8538   if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8539                    options::OPT_mno_default_build_attributes, true)) {
8540       CmdArgs.push_back("-mllvm");
8541       CmdArgs.push_back("-riscv-add-build-attributes");
8542   }
8543 }
8544 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8545 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
8546                            const InputInfo &Output, const InputInfoList &Inputs,
8547                            const ArgList &Args,
8548                            const char *LinkingOutput) const {
8549   ArgStringList CmdArgs;
8550 
8551   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8552   const InputInfo &Input = Inputs[0];
8553 
8554   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8555   const std::string &TripleStr = Triple.getTriple();
8556   const auto &D = getToolChain().getDriver();
8557 
8558   // Don't warn about "clang -w -c foo.s"
8559   Args.ClaimAllArgs(options::OPT_w);
8560   // and "clang -emit-llvm -c foo.s"
8561   Args.ClaimAllArgs(options::OPT_emit_llvm);
8562 
8563   claimNoWarnArgs(Args);
8564 
8565   // Invoke ourselves in -cc1as mode.
8566   //
8567   // FIXME: Implement custom jobs for internal actions.
8568   CmdArgs.push_back("-cc1as");
8569 
8570   // Add the "effective" target triple.
8571   CmdArgs.push_back("-triple");
8572   CmdArgs.push_back(Args.MakeArgString(TripleStr));
8573 
8574   getToolChain().addClangCC1ASTargetOptions(Args, CmdArgs);
8575 
8576   // Set the output mode, we currently only expect to be used as a real
8577   // assembler.
8578   CmdArgs.push_back("-filetype");
8579   CmdArgs.push_back("obj");
8580 
8581   // Set the main file name, so that debug info works even with
8582   // -save-temps or preprocessed assembly.
8583   CmdArgs.push_back("-main-file-name");
8584   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
8585 
8586   // Add the target cpu
8587   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
8588   if (!CPU.empty()) {
8589     CmdArgs.push_back("-target-cpu");
8590     CmdArgs.push_back(Args.MakeArgString(CPU));
8591   }
8592 
8593   // Add the target features
8594   getTargetFeatures(D, Triple, Args, CmdArgs, true);
8595 
8596   // Ignore explicit -force_cpusubtype_ALL option.
8597   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
8598 
8599   // Pass along any -I options so we get proper .include search paths.
8600   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
8601 
8602   // Pass along any --embed-dir or similar options so we get proper embed paths.
8603   Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);
8604 
8605   // Determine the original source input.
8606   auto FindSource = [](const Action *S) -> const Action * {
8607     while (S->getKind() != Action::InputClass) {
8608       assert(!S->getInputs().empty() && "unexpected root action!");
8609       S = S->getInputs()[0];
8610     }
8611     return S;
8612   };
8613   const Action *SourceAction = FindSource(&JA);
8614 
8615   // Forward -g and handle debug info related flags, assuming we are dealing
8616   // with an actual assembly file.
8617   bool WantDebug = false;
8618   Args.ClaimAllArgs(options::OPT_g_Group);
8619   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
8620     WantDebug = !A->getOption().matches(options::OPT_g0) &&
8621                 !A->getOption().matches(options::OPT_ggdb0);
8622 
8623   // If a -gdwarf argument appeared, remember it.
8624   bool EmitDwarf = false;
8625   if (const Arg *A = getDwarfNArg(Args))
8626     EmitDwarf = checkDebugInfoOption(A, Args, D, getToolChain());
8627 
8628   bool EmitCodeView = false;
8629   if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
8630     EmitCodeView = checkDebugInfoOption(A, Args, D, getToolChain());
8631 
8632   // If the user asked for debug info but did not explicitly specify -gcodeview
8633   // or -gdwarf, ask the toolchain for the default format.
8634   if (!EmitCodeView && !EmitDwarf && WantDebug) {
8635     switch (getToolChain().getDefaultDebugFormat()) {
8636     case llvm::codegenoptions::DIF_CodeView:
8637       EmitCodeView = true;
8638       break;
8639     case llvm::codegenoptions::DIF_DWARF:
8640       EmitDwarf = true;
8641       break;
8642     }
8643   }
8644 
8645   // If the arguments don't imply DWARF, don't emit any debug info here.
8646   if (!EmitDwarf)
8647     WantDebug = false;
8648 
8649   llvm::codegenoptions::DebugInfoKind DebugInfoKind =
8650       llvm::codegenoptions::NoDebugInfo;
8651 
8652   // Add the -fdebug-compilation-dir flag if needed.
8653   const char *DebugCompilationDir =
8654       addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
8655 
8656   if (SourceAction->getType() == types::TY_Asm ||
8657       SourceAction->getType() == types::TY_PP_Asm) {
8658     // You might think that it would be ok to set DebugInfoKind outside of
8659     // the guard for source type, however there is a test which asserts
8660     // that some assembler invocation receives no -debug-info-kind,
8661     // and it's not clear whether that test is just overly restrictive.
8662     DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
8663                                : llvm::codegenoptions::NoDebugInfo);
8664 
8665     addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
8666                          CmdArgs);
8667 
8668     // Set the AT_producer to the clang version when using the integrated
8669     // assembler on assembly source files.
8670     CmdArgs.push_back("-dwarf-debug-producer");
8671     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
8672 
8673     // And pass along -I options
8674     Args.AddAllArgs(CmdArgs, options::OPT_I);
8675   }
8676   const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
8677   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
8678                           llvm::DebuggerKind::Default);
8679   renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
8680   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
8681 
8682   // Handle -fPIC et al -- the relocation-model affects the assembler
8683   // for some targets.
8684   llvm::Reloc::Model RelocationModel;
8685   unsigned PICLevel;
8686   bool IsPIE;
8687   std::tie(RelocationModel, PICLevel, IsPIE) =
8688       ParsePICArgs(getToolChain(), Args);
8689 
8690   const char *RMName = RelocationModelName(RelocationModel);
8691   if (RMName) {
8692     CmdArgs.push_back("-mrelocation-model");
8693     CmdArgs.push_back(RMName);
8694   }
8695 
8696   // Optionally embed the -cc1as level arguments into the debug info, for build
8697   // analysis.
8698   if (getToolChain().UseDwarfDebugFlags()) {
8699     ArgStringList OriginalArgs;
8700     for (const auto &Arg : Args)
8701       Arg->render(Args, OriginalArgs);
8702 
8703     SmallString<256> Flags;
8704     const char *Exec = getToolChain().getDriver().getClangProgramPath();
8705     escapeSpacesAndBackslashes(Exec, Flags);
8706     for (const char *OriginalArg : OriginalArgs) {
8707       SmallString<128> EscapedArg;
8708       escapeSpacesAndBackslashes(OriginalArg, EscapedArg);
8709       Flags += " ";
8710       Flags += EscapedArg;
8711     }
8712     CmdArgs.push_back("-dwarf-debug-flags");
8713     CmdArgs.push_back(Args.MakeArgString(Flags));
8714   }
8715 
8716   // FIXME: Add -static support, once we have it.
8717 
8718   // Add target specific flags.
8719   switch (getToolChain().getArch()) {
8720   default:
8721     break;
8722 
8723   case llvm::Triple::mips:
8724   case llvm::Triple::mipsel:
8725   case llvm::Triple::mips64:
8726   case llvm::Triple::mips64el:
8727     AddMIPSTargetArgs(Args, CmdArgs);
8728     break;
8729 
8730   case llvm::Triple::x86:
8731   case llvm::Triple::x86_64:
8732     AddX86TargetArgs(Args, CmdArgs);
8733     break;
8734 
8735   case llvm::Triple::arm:
8736   case llvm::Triple::armeb:
8737   case llvm::Triple::thumb:
8738   case llvm::Triple::thumbeb:
8739     // This isn't in AddARMTargetArgs because we want to do this for assembly
8740     // only, not C/C++.
8741     if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8742                      options::OPT_mno_default_build_attributes, true)) {
8743         CmdArgs.push_back("-mllvm");
8744         CmdArgs.push_back("-arm-add-build-attributes");
8745     }
8746     break;
8747 
8748   case llvm::Triple::aarch64:
8749   case llvm::Triple::aarch64_32:
8750   case llvm::Triple::aarch64_be:
8751     if (Args.hasArg(options::OPT_mmark_bti_property)) {
8752       CmdArgs.push_back("-mllvm");
8753       CmdArgs.push_back("-aarch64-mark-bti-property");
8754     }
8755     break;
8756 
8757   case llvm::Triple::loongarch32:
8758   case llvm::Triple::loongarch64:
8759     AddLoongArchTargetArgs(Args, CmdArgs);
8760     break;
8761 
8762   case llvm::Triple::riscv32:
8763   case llvm::Triple::riscv64:
8764     AddRISCVTargetArgs(Args, CmdArgs);
8765     break;
8766 
8767   case llvm::Triple::hexagon:
8768     if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8769                      options::OPT_mno_default_build_attributes, true)) {
8770       CmdArgs.push_back("-mllvm");
8771       CmdArgs.push_back("-hexagon-add-build-attributes");
8772     }
8773     break;
8774   }
8775 
8776   // Consume all the warning flags. Usually this would be handled more
8777   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
8778   // doesn't handle that so rather than warning about unused flags that are
8779   // actually used, we'll lie by omission instead.
8780   // FIXME: Stop lying and consume only the appropriate driver flags
8781   Args.ClaimAllArgs(options::OPT_W_Group);
8782 
8783   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
8784                                     getToolChain().getDriver());
8785 
8786   // Forward -Xclangas arguments to -cc1as
8787   for (auto Arg : Args.filtered(options::OPT_Xclangas)) {
8788     Arg->claim();
8789     CmdArgs.push_back(Arg->getValue());
8790   }
8791 
8792   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
8793 
8794   if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
8795     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
8796                        Output.getFilename());
8797 
8798   // Fixup any previous commands that use -object-file-name because when we
8799   // generated them, the final .obj name wasn't yet known.
8800   for (Command &J : C.getJobs()) {
8801     if (SourceAction != FindSource(&J.getSource()))
8802       continue;
8803     auto &JArgs = J.getArguments();
8804     for (unsigned I = 0; I < JArgs.size(); ++I) {
8805       if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
8806           Output.isFilename()) {
8807        ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
8808        addDebugObjectName(Args, NewArgs, DebugCompilationDir,
8809                           Output.getFilename());
8810        NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
8811        J.replaceArguments(NewArgs);
8812        break;
8813       }
8814     }
8815   }
8816 
8817   assert(Output.isFilename() && "Unexpected lipo output.");
8818   CmdArgs.push_back("-o");
8819   CmdArgs.push_back(Output.getFilename());
8820 
8821   const llvm::Triple &T = getToolChain().getTriple();
8822   Arg *A;
8823   if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
8824       T.isOSBinFormatELF()) {
8825     CmdArgs.push_back("-split-dwarf-output");
8826     CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
8827   }
8828 
8829   if (Triple.isAMDGPU())
8830     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8831 
8832   assert(Input.isFilename() && "Invalid input.");
8833   CmdArgs.push_back(Input.getFilename());
8834 
8835   const char *Exec = getToolChain().getDriver().getClangProgramPath();
8836   if (D.CC1Main && !D.CCGenDiagnostics) {
8837     // Invoke cc1as directly in this process.
8838     C.addCommand(std::make_unique<CC1Command>(
8839         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8840         Output, D.getPrependArg()));
8841   } else {
8842     C.addCommand(std::make_unique<Command>(
8843         JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8844         Output, D.getPrependArg()));
8845   }
8846 }
8847 
8848 // Begin OffloadBundler
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const llvm::opt::ArgList & TCArgs,const char * LinkingOutput) const8849 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
8850                                   const InputInfo &Output,
8851                                   const InputInfoList &Inputs,
8852                                   const llvm::opt::ArgList &TCArgs,
8853                                   const char *LinkingOutput) const {
8854   // The version with only one output is expected to refer to a bundling job.
8855   assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
8856 
8857   // The bundling command looks like this:
8858   // clang-offload-bundler -type=bc
8859   //   -targets=host-triple,openmp-triple1,openmp-triple2
8860   //   -output=output_file
8861   //   -input=unbundle_file_host
8862   //   -input=unbundle_file_tgt1
8863   //   -input=unbundle_file_tgt2
8864 
8865   ArgStringList CmdArgs;
8866 
8867   // Get the type.
8868   CmdArgs.push_back(TCArgs.MakeArgString(
8869       Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
8870 
8871   assert(JA.getInputs().size() == Inputs.size() &&
8872          "Not have inputs for all dependence actions??");
8873 
8874   // Get the targets.
8875   SmallString<128> Triples;
8876   Triples += "-targets=";
8877   for (unsigned I = 0; I < Inputs.size(); ++I) {
8878     if (I)
8879       Triples += ',';
8880 
8881     // Find ToolChain for this input.
8882     Action::OffloadKind CurKind = Action::OFK_Host;
8883     const ToolChain *CurTC = &getToolChain();
8884     const Action *CurDep = JA.getInputs()[I];
8885 
8886     if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
8887       CurTC = nullptr;
8888       OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
8889         assert(CurTC == nullptr && "Expected one dependence!");
8890         CurKind = A->getOffloadingDeviceKind();
8891         CurTC = TC;
8892       });
8893     }
8894     Triples += Action::GetOffloadKindName(CurKind);
8895     Triples += '-';
8896     Triples +=
8897         CurTC->getTriple().normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
8898     if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
8899         !StringRef(CurDep->getOffloadingArch()).empty()) {
8900       Triples += '-';
8901       Triples += CurDep->getOffloadingArch();
8902     }
8903 
8904     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8905     //       with each toolchain.
8906     StringRef GPUArchName;
8907     if (CurKind == Action::OFK_OpenMP) {
8908       // Extract GPUArch from -march argument in TC argument list.
8909       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8910         auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
8911         auto Arch = ArchStr.starts_with_insensitive("-march=");
8912         if (Arch) {
8913           GPUArchName = ArchStr.substr(7);
8914           Triples += "-";
8915           break;
8916         }
8917       }
8918       Triples += GPUArchName.str();
8919     }
8920   }
8921   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8922 
8923   // Get bundled file command.
8924   CmdArgs.push_back(
8925       TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
8926 
8927   // Get unbundled files command.
8928   for (unsigned I = 0; I < Inputs.size(); ++I) {
8929     SmallString<128> UB;
8930     UB += "-input=";
8931 
8932     // Find ToolChain for this input.
8933     const ToolChain *CurTC = &getToolChain();
8934     if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
8935       CurTC = nullptr;
8936       OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
8937         assert(CurTC == nullptr && "Expected one dependence!");
8938         CurTC = TC;
8939       });
8940       UB += C.addTempFile(
8941           C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
8942     } else {
8943       UB += CurTC->getInputFilename(Inputs[I]);
8944     }
8945     CmdArgs.push_back(TCArgs.MakeArgString(UB));
8946   }
8947   addOffloadCompressArgs(TCArgs, CmdArgs);
8948   // All the inputs are encoded as commands.
8949   C.addCommand(std::make_unique<Command>(
8950       JA, *this, ResponseFileSupport::None(),
8951       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8952       CmdArgs, ArrayRef<InputInfo>(), Output));
8953 }
8954 
ConstructJobMultipleOutputs(Compilation & C,const JobAction & JA,const InputInfoList & Outputs,const InputInfoList & Inputs,const llvm::opt::ArgList & TCArgs,const char * LinkingOutput) const8955 void OffloadBundler::ConstructJobMultipleOutputs(
8956     Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
8957     const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
8958     const char *LinkingOutput) const {
8959   // The version with multiple outputs is expected to refer to a unbundling job.
8960   auto &UA = cast<OffloadUnbundlingJobAction>(JA);
8961 
8962   // The unbundling command looks like this:
8963   // clang-offload-bundler -type=bc
8964   //   -targets=host-triple,openmp-triple1,openmp-triple2
8965   //   -input=input_file
8966   //   -output=unbundle_file_host
8967   //   -output=unbundle_file_tgt1
8968   //   -output=unbundle_file_tgt2
8969   //   -unbundle
8970 
8971   ArgStringList CmdArgs;
8972 
8973   assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
8974   InputInfo Input = Inputs.front();
8975 
8976   // Get the type.
8977   CmdArgs.push_back(TCArgs.MakeArgString(
8978       Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
8979 
8980   // Get the targets.
8981   SmallString<128> Triples;
8982   Triples += "-targets=";
8983   auto DepInfo = UA.getDependentActionsInfo();
8984   for (unsigned I = 0; I < DepInfo.size(); ++I) {
8985     if (I)
8986       Triples += ',';
8987 
8988     auto &Dep = DepInfo[I];
8989     Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
8990     Triples += '-';
8991     Triples += Dep.DependentToolChain->getTriple().normalize(
8992         llvm::Triple::CanonicalForm::FOUR_IDENT);
8993     if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
8994          Dep.DependentOffloadKind == Action::OFK_Cuda) &&
8995         !Dep.DependentBoundArch.empty()) {
8996       Triples += '-';
8997       Triples += Dep.DependentBoundArch;
8998     }
8999     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
9000     //       with each toolchain.
9001     StringRef GPUArchName;
9002     if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
9003       // Extract GPUArch from -march argument in TC argument list.
9004       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
9005         StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
9006         auto Arch = ArchStr.starts_with_insensitive("-march=");
9007         if (Arch) {
9008           GPUArchName = ArchStr.substr(7);
9009           Triples += "-";
9010           break;
9011         }
9012       }
9013       Triples += GPUArchName.str();
9014     }
9015   }
9016 
9017   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9018 
9019   // Get bundled file command.
9020   CmdArgs.push_back(
9021       TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
9022 
9023   // Get unbundled files command.
9024   for (unsigned I = 0; I < Outputs.size(); ++I) {
9025     SmallString<128> UB;
9026     UB += "-output=";
9027     UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
9028     CmdArgs.push_back(TCArgs.MakeArgString(UB));
9029   }
9030   CmdArgs.push_back("-unbundle");
9031   CmdArgs.push_back("-allow-missing-bundles");
9032   if (TCArgs.hasArg(options::OPT_v))
9033     CmdArgs.push_back("-verbose");
9034 
9035   // All the inputs are encoded as commands.
9036   C.addCommand(std::make_unique<Command>(
9037       JA, *this, ResponseFileSupport::None(),
9038       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9039       CmdArgs, ArrayRef<InputInfo>(), Outputs));
9040 }
9041 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const llvm::opt::ArgList & Args,const char * LinkingOutput) const9042 void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
9043                                    const InputInfo &Output,
9044                                    const InputInfoList &Inputs,
9045                                    const llvm::opt::ArgList &Args,
9046                                    const char *LinkingOutput) const {
9047   ArgStringList CmdArgs;
9048 
9049   // Add the output file name.
9050   assert(Output.isFilename() && "Invalid output.");
9051   CmdArgs.push_back("-o");
9052   CmdArgs.push_back(Output.getFilename());
9053 
9054   // Create the inputs to bundle the needed metadata.
9055   for (const InputInfo &Input : Inputs) {
9056     const Action *OffloadAction = Input.getAction();
9057     const ToolChain *TC = OffloadAction->getOffloadingToolChain();
9058     const ArgList &TCArgs =
9059         C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
9060                               OffloadAction->getOffloadingDeviceKind());
9061     StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
9062     StringRef Arch = OffloadAction->getOffloadingArch()
9063                          ? OffloadAction->getOffloadingArch()
9064                          : TCArgs.getLastArgValue(options::OPT_march_EQ);
9065     StringRef Kind =
9066       Action::GetOffloadKindName(OffloadAction->getOffloadingDeviceKind());
9067 
9068     ArgStringList Features;
9069     SmallVector<StringRef> FeatureArgs;
9070     getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
9071                       false);
9072     llvm::copy_if(Features, std::back_inserter(FeatureArgs),
9073                   [](StringRef Arg) { return !Arg.starts_with("-target"); });
9074 
9075     // TODO: We need to pass in the full target-id and handle it properly in the
9076     // linker wrapper.
9077     SmallVector<std::string> Parts{
9078         "file=" + File.str(),
9079         "triple=" + TC->getTripleString(),
9080         "arch=" + (Arch.empty() ? "generic" : Arch.str()),
9081         "kind=" + Kind.str(),
9082     };
9083 
9084     if (TC->getDriver().isUsingOffloadLTO())
9085       for (StringRef Feature : FeatureArgs)
9086         Parts.emplace_back("feature=" + Feature.str());
9087 
9088     CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
9089   }
9090 
9091   C.addCommand(std::make_unique<Command>(
9092       JA, *this, ResponseFileSupport::None(),
9093       Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9094       CmdArgs, Inputs, Output));
9095 }
9096 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9097 void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
9098                                  const InputInfo &Output,
9099                                  const InputInfoList &Inputs,
9100                                  const ArgList &Args,
9101                                  const char *LinkingOutput) const {
9102   using namespace options;
9103 
9104   // A list of permitted options that will be forwarded to the embedded device
9105   // compilation job.
9106   const llvm::DenseSet<unsigned> CompilerOptions{
9107       OPT_v,
9108       OPT_cuda_path_EQ,
9109       OPT_rocm_path_EQ,
9110       OPT_O_Group,
9111       OPT_g_Group,
9112       OPT_g_flags_Group,
9113       OPT_R_value_Group,
9114       OPT_R_Group,
9115       OPT_Xcuda_ptxas,
9116       OPT_ftime_report,
9117       OPT_ftime_trace,
9118       OPT_ftime_trace_EQ,
9119       OPT_ftime_trace_granularity_EQ,
9120       OPT_ftime_trace_verbose,
9121       OPT_opt_record_file,
9122       OPT_opt_record_format,
9123       OPT_opt_record_passes,
9124       OPT_fsave_optimization_record,
9125       OPT_fsave_optimization_record_EQ,
9126       OPT_fno_save_optimization_record,
9127       OPT_foptimization_record_file_EQ,
9128       OPT_foptimization_record_passes_EQ,
9129       OPT_save_temps,
9130       OPT_save_temps_EQ,
9131       OPT_mcode_object_version_EQ,
9132       OPT_load,
9133       OPT_fno_lto,
9134       OPT_flto,
9135       OPT_flto_partitions_EQ,
9136       OPT_flto_EQ};
9137   const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9138   auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A) {
9139     return Set.contains(A->getOption().getID()) ||
9140            (A->getOption().getGroup().isValid() &&
9141             Set.contains(A->getOption().getGroup().getID()));
9142   };
9143 
9144   ArgStringList CmdArgs;
9145   for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
9146                                    Action::OFK_HIP, Action::OFK_SYCL}) {
9147     auto TCRange = C.getOffloadToolChains(Kind);
9148     for (auto &I : llvm::make_range(TCRange)) {
9149       const ToolChain *TC = I.second;
9150 
9151       // We do not use a bound architecture here so options passed only to a
9152       // specific architecture via -Xarch_<cpu> will not be forwarded.
9153       ArgStringList CompilerArgs;
9154       ArgStringList LinkerArgs;
9155       const DerivedArgList &ToolChainArgs =
9156           C.getArgsForToolChain(TC, /*BoundArch=*/"", Kind);
9157       for (Arg *A : ToolChainArgs) {
9158         if (A->getOption().matches(OPT_Zlinker_input))
9159           LinkerArgs.emplace_back(A->getValue());
9160         else if (ShouldForward(CompilerOptions, A))
9161           A->render(Args, CompilerArgs);
9162         else if (ShouldForward(LinkerOptions, A))
9163           A->render(Args, LinkerArgs);
9164       }
9165 
9166       // If the user explicitly requested it via `--offload-arch` we should
9167       // extract it from any static libraries if present.
9168       for (StringRef Arg : ToolChainArgs.getAllArgValues(OPT_offload_arch_EQ))
9169         CmdArgs.emplace_back(Args.MakeArgString("--should-extract=" + Arg));
9170 
9171       // If this is OpenMP the device linker will need `-lompdevice`.
9172       if (Kind == Action::OFK_OpenMP && !Args.hasArg(OPT_no_offloadlib) &&
9173           (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9174         LinkerArgs.emplace_back("-lompdevice");
9175 
9176       // Forward all of these to the appropriate toolchain.
9177       for (StringRef Arg : CompilerArgs)
9178         CmdArgs.push_back(Args.MakeArgString(
9179             "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9180       for (StringRef Arg : LinkerArgs)
9181         CmdArgs.push_back(Args.MakeArgString(
9182             "--device-linker=" + TC->getTripleString() + "=" + Arg));
9183 
9184       // Forward the LTO mode relying on the Driver's parsing.
9185       if (C.getDriver().getOffloadLTOMode() == LTOK_Full)
9186         CmdArgs.push_back(Args.MakeArgString(
9187             "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9188       else if (C.getDriver().getOffloadLTOMode() == LTOK_Thin) {
9189         CmdArgs.push_back(Args.MakeArgString(
9190             "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9191         if (TC->getTriple().isAMDGPU()) {
9192           CmdArgs.push_back(
9193               Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9194                                  "=-plugin-opt=-force-import-all"));
9195           CmdArgs.push_back(
9196               Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9197                                  "=-plugin-opt=-avail-extern-to-local"));
9198           CmdArgs.push_back(Args.MakeArgString(
9199               "--device-linker=" + TC->getTripleString() +
9200               "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
9201           if (Kind == Action::OFK_OpenMP) {
9202             CmdArgs.push_back(
9203                 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9204                                    "=-plugin-opt=-amdgpu-internalize-symbols"));
9205           }
9206         }
9207       }
9208     }
9209   }
9210 
9211   CmdArgs.push_back(
9212       Args.MakeArgString("--host-triple=" + getToolChain().getTripleString()));
9213   if (Args.hasArg(options::OPT_v))
9214     CmdArgs.push_back("--wrapper-verbose");
9215   if (Arg *A = Args.getLastArg(options::OPT_cuda_path_EQ))
9216     CmdArgs.push_back(
9217         Args.MakeArgString(Twine("--cuda-path=") + A->getValue()));
9218 
9219   // Construct the link job so we can wrap around it.
9220   Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
9221   const auto &LinkCommand = C.getJobs().getJobs().back();
9222 
9223   // Forward -Xoffload-linker<-triple> arguments to the device link job.
9224   for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {
9225     StringRef Val = A->getValue(0);
9226     if (Val.empty())
9227       CmdArgs.push_back(
9228           Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));
9229     else
9230       CmdArgs.push_back(Args.MakeArgString(
9231           "--device-linker=" +
9232           ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +
9233           A->getValue(1)));
9234   }
9235   Args.ClaimAllArgs(options::OPT_Xoffload_linker);
9236 
9237   // Embed bitcode instead of an object in JIT mode.
9238   if (Args.hasFlag(options::OPT_fopenmp_target_jit,
9239                    options::OPT_fno_openmp_target_jit, false))
9240     CmdArgs.push_back("--embed-bitcode");
9241 
9242   // Save temporary files created by the linker wrapper.
9243   if (Args.hasArg(options::OPT_save_temps_EQ) ||
9244       Args.hasArg(options::OPT_save_temps))
9245     CmdArgs.push_back("--save-temps");
9246 
9247   // Pass in the C library for GPUs if present and not disabled.
9248   if (Args.hasFlag(options::OPT_offloadlib, OPT_no_offloadlib, true) &&
9249       !Args.hasArg(options::OPT_nostdlib, options::OPT_r,
9250                    options::OPT_nodefaultlibs, options::OPT_nolibc,
9251                    options::OPT_nogpulibc)) {
9252     forAllAssociatedToolChains(C, JA, getToolChain(), [&](const ToolChain &TC) {
9253       // The device C library is only available for NVPTX and AMDGPU targets
9254       // currently.
9255       if (!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU())
9256         return;
9257       bool HasLibC = TC.getStdlibIncludePath().has_value();
9258       if (HasLibC) {
9259         CmdArgs.push_back(Args.MakeArgString(
9260             "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
9261         CmdArgs.push_back(Args.MakeArgString(
9262             "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
9263       }
9264       auto HasCompilerRT = getToolChain().getVFS().exists(
9265           TC.getCompilerRT(Args, "builtins", ToolChain::FT_Static));
9266       if (HasCompilerRT)
9267         CmdArgs.push_back(
9268             Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
9269                                "-lclang_rt.builtins"));
9270       bool HasFlangRT = HasCompilerRT && C.getDriver().IsFlangMode();
9271       if (HasFlangRT)
9272         CmdArgs.push_back(
9273             Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
9274                                "-lflang_rt.runtime"));
9275     });
9276   }
9277 
9278   // Add the linker arguments to be forwarded by the wrapper.
9279   CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
9280                                        LinkCommand->getExecutable()));
9281 
9282   // We use action type to differentiate two use cases of the linker wrapper.
9283   // TY_Image for normal linker wrapper work.
9284   // TY_Object for HIP fno-gpu-rdc embedding device binary in a relocatable
9285   // object.
9286   assert(JA.getType() == types::TY_Object || JA.getType() == types::TY_Image);
9287   if (JA.getType() == types::TY_Object) {
9288     CmdArgs.append({"-o", Output.getFilename()});
9289     for (auto Input : Inputs)
9290       CmdArgs.push_back(Input.getFilename());
9291     CmdArgs.push_back("-r");
9292   } else
9293     for (const char *LinkArg : LinkCommand->getArguments())
9294       CmdArgs.push_back(LinkArg);
9295 
9296   addOffloadCompressArgs(Args, CmdArgs);
9297 
9298   if (Arg *A = Args.getLastArg(options::OPT_offload_jobs_EQ)) {
9299     int NumThreads;
9300     if (StringRef(A->getValue()).getAsInteger(10, NumThreads) ||
9301         NumThreads <= 0)
9302       C.getDriver().Diag(diag::err_drv_invalid_int_value)
9303           << A->getAsString(Args) << A->getValue();
9304     else
9305       CmdArgs.push_back(
9306           Args.MakeArgString("--wrapper-jobs=" + Twine(NumThreads)));
9307   }
9308 
9309   const char *Exec =
9310       Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
9311 
9312   // Replace the executable and arguments of the link job with the
9313   // wrapper.
9314   LinkCommand->replaceExecutable(Exec);
9315   LinkCommand->replaceArguments(CmdArgs);
9316 }
9317