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