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