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