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