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