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