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