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