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