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