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