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