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