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