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