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