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.
3171     if (Triple.isPS4()) {
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.isPS4()) {
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     }
4598   } else if (isa<AssembleJobAction>(JA)) {
4599     CmdArgs.push_back("-emit-obj");
4600 
4601     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
4602 
4603     // Also ignore explicit -force_cpusubtype_ALL option.
4604     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4605   } else if (isa<PrecompileJobAction>(JA)) {
4606     if (JA.getType() == types::TY_Nothing)
4607       CmdArgs.push_back("-fsyntax-only");
4608     else if (JA.getType() == types::TY_ModuleFile)
4609       CmdArgs.push_back(IsHeaderModulePrecompile
4610                             ? "-emit-header-module"
4611                             : "-emit-module-interface");
4612     else
4613       CmdArgs.push_back("-emit-pch");
4614   } else if (isa<VerifyPCHJobAction>(JA)) {
4615     CmdArgs.push_back("-verify-pch");
4616   } else if (isa<ExtractAPIJobAction>(JA)) {
4617     assert(JA.getType() == types::TY_API_INFO &&
4618            "Extract API actions must generate a API information.");
4619     CmdArgs.push_back("-extract-api");
4620     if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
4621       ProductNameArg->render(Args, CmdArgs);
4622   } else {
4623     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
4624            "Invalid action for clang tool.");
4625     if (JA.getType() == types::TY_Nothing) {
4626       CmdArgs.push_back("-fsyntax-only");
4627     } else if (JA.getType() == types::TY_LLVM_IR ||
4628                JA.getType() == types::TY_LTO_IR) {
4629       CmdArgs.push_back("-emit-llvm");
4630     } else if (JA.getType() == types::TY_LLVM_BC ||
4631                JA.getType() == types::TY_LTO_BC) {
4632       // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
4633       if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
4634           Args.hasArg(options::OPT_emit_llvm)) {
4635         CmdArgs.push_back("-emit-llvm");
4636       } else {
4637         CmdArgs.push_back("-emit-llvm-bc");
4638       }
4639     } else if (JA.getType() == types::TY_IFS ||
4640                JA.getType() == types::TY_IFS_CPP) {
4641       StringRef ArgStr =
4642           Args.hasArg(options::OPT_interface_stub_version_EQ)
4643               ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4644               : "ifs-v1";
4645       CmdArgs.push_back("-emit-interface-stubs");
4646       CmdArgs.push_back(
4647           Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
4648     } else if (JA.getType() == types::TY_PP_Asm) {
4649       CmdArgs.push_back("-S");
4650     } else if (JA.getType() == types::TY_AST) {
4651       CmdArgs.push_back("-emit-pch");
4652     } else if (JA.getType() == types::TY_ModuleFile) {
4653       CmdArgs.push_back("-module-file-info");
4654     } else if (JA.getType() == types::TY_RewrittenObjC) {
4655       CmdArgs.push_back("-rewrite-objc");
4656       rewriteKind = RK_NonFragile;
4657     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
4658       CmdArgs.push_back("-rewrite-objc");
4659       rewriteKind = RK_Fragile;
4660     } else {
4661       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
4662     }
4663 
4664     // Preserve use-list order by default when emitting bitcode, so that
4665     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
4666     // same result as running passes here.  For LTO, we don't need to preserve
4667     // the use-list order, since serialization to bitcode is part of the flow.
4668     if (JA.getType() == types::TY_LLVM_BC)
4669       CmdArgs.push_back("-emit-llvm-uselists");
4670 
4671     if (IsUsingLTO) {
4672       // Only AMDGPU supports device-side LTO.
4673       if (IsDeviceOffloadAction &&
4674           Args.hasArg(options::OPT_fno_openmp_new_driver) &&
4675           !Triple.isAMDGPU()) {
4676         D.Diag(diag::err_drv_unsupported_opt_for_target)
4677             << Args.getLastArg(options::OPT_foffload_lto,
4678                                options::OPT_foffload_lto_EQ)
4679                    ->getAsString(Args)
4680             << Triple.getTriple();
4681       } else {
4682         assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
4683         CmdArgs.push_back(Args.MakeArgString(
4684             Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
4685         CmdArgs.push_back("-flto-unit");
4686       }
4687     }
4688   }
4689 
4690   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
4691     if (!types::isLLVMIR(Input.getType()))
4692       D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
4693     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
4694   }
4695 
4696   if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
4697     Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
4698 
4699   if (Args.getLastArg(options::OPT_save_temps_EQ))
4700     Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
4701 
4702   auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
4703                                      options::OPT_fmemory_profile_EQ,
4704                                      options::OPT_fno_memory_profile);
4705   if (MemProfArg &&
4706       !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
4707     MemProfArg->render(Args, CmdArgs);
4708 
4709   // Embed-bitcode option.
4710   // Only white-listed flags below are allowed to be embedded.
4711   if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
4712       (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
4713     // Add flags implied by -fembed-bitcode.
4714     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
4715     // Disable all llvm IR level optimizations.
4716     CmdArgs.push_back("-disable-llvm-passes");
4717 
4718     // Render target options.
4719     TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4720 
4721     // reject options that shouldn't be supported in bitcode
4722     // also reject kernel/kext
4723     static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
4724         options::OPT_mkernel,
4725         options::OPT_fapple_kext,
4726         options::OPT_ffunction_sections,
4727         options::OPT_fno_function_sections,
4728         options::OPT_fdata_sections,
4729         options::OPT_fno_data_sections,
4730         options::OPT_fbasic_block_sections_EQ,
4731         options::OPT_funique_internal_linkage_names,
4732         options::OPT_fno_unique_internal_linkage_names,
4733         options::OPT_funique_section_names,
4734         options::OPT_fno_unique_section_names,
4735         options::OPT_funique_basic_block_section_names,
4736         options::OPT_fno_unique_basic_block_section_names,
4737         options::OPT_mrestrict_it,
4738         options::OPT_mno_restrict_it,
4739         options::OPT_mstackrealign,
4740         options::OPT_mno_stackrealign,
4741         options::OPT_mstack_alignment,
4742         options::OPT_mcmodel_EQ,
4743         options::OPT_mlong_calls,
4744         options::OPT_mno_long_calls,
4745         options::OPT_ggnu_pubnames,
4746         options::OPT_gdwarf_aranges,
4747         options::OPT_fdebug_types_section,
4748         options::OPT_fno_debug_types_section,
4749         options::OPT_fdwarf_directory_asm,
4750         options::OPT_fno_dwarf_directory_asm,
4751         options::OPT_mrelax_all,
4752         options::OPT_mno_relax_all,
4753         options::OPT_ftrap_function_EQ,
4754         options::OPT_ffixed_r9,
4755         options::OPT_mfix_cortex_a53_835769,
4756         options::OPT_mno_fix_cortex_a53_835769,
4757         options::OPT_ffixed_x18,
4758         options::OPT_mglobal_merge,
4759         options::OPT_mno_global_merge,
4760         options::OPT_mred_zone,
4761         options::OPT_mno_red_zone,
4762         options::OPT_Wa_COMMA,
4763         options::OPT_Xassembler,
4764         options::OPT_mllvm,
4765     };
4766     for (const auto &A : Args)
4767       if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
4768         D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
4769 
4770     // Render the CodeGen options that need to be passed.
4771     Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
4772                        options::OPT_fno_optimize_sibling_calls);
4773 
4774     RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
4775                                CmdArgs, JA);
4776 
4777     // Render ABI arguments
4778     switch (TC.getArch()) {
4779     default: break;
4780     case llvm::Triple::arm:
4781     case llvm::Triple::armeb:
4782     case llvm::Triple::thumbeb:
4783       RenderARMABI(D, Triple, Args, CmdArgs);
4784       break;
4785     case llvm::Triple::aarch64:
4786     case llvm::Triple::aarch64_32:
4787     case llvm::Triple::aarch64_be:
4788       RenderAArch64ABI(Triple, Args, CmdArgs);
4789       break;
4790     }
4791 
4792     // Optimization level for CodeGen.
4793     if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4794       if (A->getOption().matches(options::OPT_O4)) {
4795         CmdArgs.push_back("-O3");
4796         D.Diag(diag::warn_O4_is_O3);
4797       } else {
4798         A->render(Args, CmdArgs);
4799       }
4800     }
4801 
4802     // Input/Output file.
4803     if (Output.getType() == types::TY_Dependencies) {
4804       // Handled with other dependency code.
4805     } else if (Output.isFilename()) {
4806       CmdArgs.push_back("-o");
4807       CmdArgs.push_back(Output.getFilename());
4808     } else {
4809       assert(Output.isNothing() && "Input output.");
4810     }
4811 
4812     for (const auto &II : Inputs) {
4813       addDashXForInput(Args, II, CmdArgs);
4814       if (II.isFilename())
4815         CmdArgs.push_back(II.getFilename());
4816       else
4817         II.getInputArg().renderAsInput(Args, CmdArgs);
4818     }
4819 
4820     C.addCommand(std::make_unique<Command>(
4821         JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
4822         CmdArgs, Inputs, Output));
4823     return;
4824   }
4825 
4826   if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
4827     CmdArgs.push_back("-fembed-bitcode=marker");
4828 
4829   // We normally speed up the clang process a bit by skipping destructors at
4830   // exit, but when we're generating diagnostics we can rely on some of the
4831   // cleanup.
4832   if (!C.isForDiagnostics())
4833     CmdArgs.push_back("-disable-free");
4834   CmdArgs.push_back("-clear-ast-before-backend");
4835 
4836 #ifdef NDEBUG
4837   const bool IsAssertBuild = false;
4838 #else
4839   const bool IsAssertBuild = true;
4840 #endif
4841 
4842   // Disable the verification pass in -asserts builds.
4843   if (!IsAssertBuild)
4844     CmdArgs.push_back("-disable-llvm-verifier");
4845 
4846   // Discard value names in assert builds unless otherwise specified.
4847   if (Args.hasFlag(options::OPT_fdiscard_value_names,
4848                    options::OPT_fno_discard_value_names, !IsAssertBuild)) {
4849     if (Args.hasArg(options::OPT_fdiscard_value_names) &&
4850         llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
4851           return types::isLLVMIR(II.getType());
4852         })) {
4853       D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
4854     }
4855     CmdArgs.push_back("-discard-value-names");
4856   }
4857 
4858   // Set the main file name, so that debug info works even with
4859   // -save-temps.
4860   CmdArgs.push_back("-main-file-name");
4861   CmdArgs.push_back(getBaseInputName(Args, Input));
4862 
4863   // Some flags which affect the language (via preprocessor
4864   // defines).
4865   if (Args.hasArg(options::OPT_static))
4866     CmdArgs.push_back("-static-define");
4867 
4868   if (Args.hasArg(options::OPT_municode))
4869     CmdArgs.push_back("-DUNICODE");
4870 
4871   if (isa<AnalyzeJobAction>(JA))
4872     RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
4873 
4874   if (isa<AnalyzeJobAction>(JA) ||
4875       (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
4876     CmdArgs.push_back("-setup-static-analyzer");
4877 
4878   // Enable compatilibily mode to avoid analyzer-config related errors.
4879   // Since we can't access frontend flags through hasArg, let's manually iterate
4880   // through them.
4881   bool FoundAnalyzerConfig = false;
4882   for (auto Arg : Args.filtered(options::OPT_Xclang))
4883     if (StringRef(Arg->getValue()) == "-analyzer-config") {
4884       FoundAnalyzerConfig = true;
4885       break;
4886     }
4887   if (!FoundAnalyzerConfig)
4888     for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
4889       if (StringRef(Arg->getValue()) == "-analyzer-config") {
4890         FoundAnalyzerConfig = true;
4891         break;
4892       }
4893   if (FoundAnalyzerConfig)
4894     CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
4895 
4896   CheckCodeGenerationOptions(D, Args);
4897 
4898   unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
4899   assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
4900   if (FunctionAlignment) {
4901     CmdArgs.push_back("-function-alignment");
4902     CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
4903   }
4904 
4905   // We support -falign-loops=N where N is a power of 2. GCC supports more
4906   // forms.
4907   if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
4908     unsigned Value = 0;
4909     if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
4910       TC.getDriver().Diag(diag::err_drv_invalid_int_value)
4911           << A->getAsString(Args) << A->getValue();
4912     else if (Value & (Value - 1))
4913       TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
4914           << A->getAsString(Args) << A->getValue();
4915     // Treat =0 as unspecified (use the target preference).
4916     if (Value)
4917       CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
4918                                            Twine(std::min(Value, 65536u))));
4919   }
4920 
4921   llvm::Reloc::Model RelocationModel;
4922   unsigned PICLevel;
4923   bool IsPIE;
4924   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
4925 
4926   bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
4927                 RelocationModel == llvm::Reloc::ROPI_RWPI;
4928   bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
4929                 RelocationModel == llvm::Reloc::ROPI_RWPI;
4930 
4931   if (Args.hasArg(options::OPT_mcmse) &&
4932       !Args.hasArg(options::OPT_fallow_unsupported)) {
4933     if (IsROPI)
4934       D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
4935     if (IsRWPI)
4936       D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
4937   }
4938 
4939   if (IsROPI && types::isCXX(Input.getType()) &&
4940       !Args.hasArg(options::OPT_fallow_unsupported))
4941     D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
4942 
4943   const char *RMName = RelocationModelName(RelocationModel);
4944   if (RMName) {
4945     CmdArgs.push_back("-mrelocation-model");
4946     CmdArgs.push_back(RMName);
4947   }
4948   if (PICLevel > 0) {
4949     CmdArgs.push_back("-pic-level");
4950     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
4951     if (IsPIE)
4952       CmdArgs.push_back("-pic-is-pie");
4953   }
4954 
4955   if (RelocationModel == llvm::Reloc::ROPI ||
4956       RelocationModel == llvm::Reloc::ROPI_RWPI)
4957     CmdArgs.push_back("-fropi");
4958   if (RelocationModel == llvm::Reloc::RWPI ||
4959       RelocationModel == llvm::Reloc::ROPI_RWPI)
4960     CmdArgs.push_back("-frwpi");
4961 
4962   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
4963     CmdArgs.push_back("-meabi");
4964     CmdArgs.push_back(A->getValue());
4965   }
4966 
4967   // -fsemantic-interposition is forwarded to CC1: set the
4968   // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
4969   // make default visibility external linkage definitions dso_preemptable.
4970   //
4971   // -fno-semantic-interposition: if the target supports .Lfoo$local local
4972   // aliases (make default visibility external linkage definitions dso_local).
4973   // This is the CC1 default for ELF to match COFF/Mach-O.
4974   //
4975   // Otherwise use Clang's traditional behavior: like
4976   // -fno-semantic-interposition but local aliases are not used. So references
4977   // can be interposed if not optimized out.
4978   if (Triple.isOSBinFormatELF()) {
4979     Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
4980                              options::OPT_fno_semantic_interposition);
4981     if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
4982       // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
4983       bool SupportsLocalAlias =
4984           Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
4985       if (!A)
4986         CmdArgs.push_back("-fhalf-no-semantic-interposition");
4987       else if (A->getOption().matches(options::OPT_fsemantic_interposition))
4988         A->render(Args, CmdArgs);
4989       else if (!SupportsLocalAlias)
4990         CmdArgs.push_back("-fhalf-no-semantic-interposition");
4991     }
4992   }
4993 
4994   {
4995     std::string Model;
4996     if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
4997       if (!TC.isThreadModelSupported(A->getValue()))
4998         D.Diag(diag::err_drv_invalid_thread_model_for_target)
4999             << A->getValue() << A->getAsString(Args);
5000       Model = A->getValue();
5001     } else
5002       Model = TC.getThreadModel();
5003     if (Model != "posix") {
5004       CmdArgs.push_back("-mthread-model");
5005       CmdArgs.push_back(Args.MakeArgString(Model));
5006     }
5007   }
5008 
5009   Args.AddLastArg(CmdArgs, options::OPT_fveclib);
5010 
5011   if (Args.hasFlag(options::OPT_fmerge_all_constants,
5012                    options::OPT_fno_merge_all_constants, false))
5013     CmdArgs.push_back("-fmerge-all-constants");
5014 
5015   if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
5016                    options::OPT_fdelete_null_pointer_checks, false))
5017     CmdArgs.push_back("-fno-delete-null-pointer-checks");
5018 
5019   // LLVM Code Generator Options.
5020 
5021   for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file_EQ)) {
5022     StringRef Map = A->getValue();
5023     if (!llvm::sys::fs::exists(Map)) {
5024       D.Diag(diag::err_drv_no_such_file) << Map;
5025     } else {
5026       A->render(Args, CmdArgs);
5027       A->claim();
5028     }
5029   }
5030 
5031   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_vec_extabi,
5032                                options::OPT_mabi_EQ_vec_default)) {
5033     if (!Triple.isOSAIX())
5034       D.Diag(diag::err_drv_unsupported_opt_for_target)
5035           << A->getSpelling() << RawTriple.str();
5036     if (A->getOption().getID() == options::OPT_mabi_EQ_vec_extabi)
5037       CmdArgs.push_back("-mabi=vec-extabi");
5038     else
5039       CmdArgs.push_back("-mabi=vec-default");
5040   }
5041 
5042   if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5043     // Emit the unsupported option error until the Clang's library integration
5044     // support for 128-bit long double is available for AIX.
5045     if (Triple.isOSAIX())
5046       D.Diag(diag::err_drv_unsupported_opt_for_target)
5047           << A->getSpelling() << RawTriple.str();
5048   }
5049 
5050   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5051     StringRef v = A->getValue();
5052     // FIXME: Validate the argument here so we don't produce meaningless errors
5053     // about -fwarn-stack-size=.
5054     if (v.empty())
5055       D.Diag(diag::err_drv_missing_argument) << A->getSpelling() << 1;
5056     else
5057       CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + v));
5058     A->claim();
5059   }
5060 
5061   Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
5062                      options::OPT_fno_jump_tables);
5063   Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
5064                     options::OPT_fno_profile_sample_accurate);
5065   Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
5066                      options::OPT_fno_preserve_as_comments);
5067 
5068   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5069     CmdArgs.push_back("-mregparm");
5070     CmdArgs.push_back(A->getValue());
5071   }
5072 
5073   if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5074                                options::OPT_msvr4_struct_return)) {
5075     if (!TC.getTriple().isPPC32()) {
5076       D.Diag(diag::err_drv_unsupported_opt_for_target)
5077           << A->getSpelling() << RawTriple.str();
5078     } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5079       CmdArgs.push_back("-maix-struct-return");
5080     } else {
5081       assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5082       CmdArgs.push_back("-msvr4-struct-return");
5083     }
5084   }
5085 
5086   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5087                                options::OPT_freg_struct_return)) {
5088     if (TC.getArch() != llvm::Triple::x86) {
5089       D.Diag(diag::err_drv_unsupported_opt_for_target)
5090           << A->getSpelling() << RawTriple.str();
5091     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5092       CmdArgs.push_back("-fpcc-struct-return");
5093     } else {
5094       assert(A->getOption().matches(options::OPT_freg_struct_return));
5095       CmdArgs.push_back("-freg-struct-return");
5096     }
5097   }
5098 
5099   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
5100     CmdArgs.push_back("-fdefault-calling-conv=stdcall");
5101 
5102   if (Args.hasArg(options::OPT_fenable_matrix)) {
5103     // enable-matrix is needed by both the LangOpts and by LLVM.
5104     CmdArgs.push_back("-fenable-matrix");
5105     CmdArgs.push_back("-mllvm");
5106     CmdArgs.push_back("-enable-matrix");
5107   }
5108 
5109   CodeGenOptions::FramePointerKind FPKeepKind =
5110                   getFramePointerKind(Args, RawTriple);
5111   const char *FPKeepKindStr = nullptr;
5112   switch (FPKeepKind) {
5113   case CodeGenOptions::FramePointerKind::None:
5114     FPKeepKindStr = "-mframe-pointer=none";
5115     break;
5116   case CodeGenOptions::FramePointerKind::NonLeaf:
5117     FPKeepKindStr = "-mframe-pointer=non-leaf";
5118     break;
5119   case CodeGenOptions::FramePointerKind::All:
5120     FPKeepKindStr = "-mframe-pointer=all";
5121     break;
5122   }
5123   assert(FPKeepKindStr && "unknown FramePointerKind");
5124   CmdArgs.push_back(FPKeepKindStr);
5125 
5126   Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
5127                      options::OPT_fno_zero_initialized_in_bss);
5128 
5129   bool OFastEnabled = isOptimizationLevelFast(Args);
5130   // If -Ofast is the optimization level, then -fstrict-aliasing should be
5131   // enabled.  This alias option is being used to simplify the hasFlag logic.
5132   OptSpecifier StrictAliasingAliasOption =
5133       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5134   // We turn strict aliasing off by default if we're in CL mode, since MSVC
5135   // doesn't do any TBAA.
5136   bool TBAAOnByDefault = !D.IsCLMode();
5137   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
5138                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
5139     CmdArgs.push_back("-relaxed-aliasing");
5140   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
5141                     options::OPT_fno_struct_path_tbaa, true))
5142     CmdArgs.push_back("-no-struct-path-tbaa");
5143   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
5144                     options::OPT_fno_strict_enums);
5145   Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
5146                      options::OPT_fno_strict_return);
5147   Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
5148                     options::OPT_fno_allow_editor_placeholders);
5149   Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
5150                     options::OPT_fno_strict_vtable_pointers);
5151   Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
5152                     options::OPT_fno_force_emit_vtables);
5153   Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5154                      options::OPT_fno_optimize_sibling_calls);
5155   Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
5156                      options::OPT_fno_escaping_block_tail_calls);
5157 
5158   Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
5159                   options::OPT_fno_fine_grained_bitfield_accesses);
5160 
5161   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5162                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
5163 
5164   // Handle segmented stacks.
5165   if (Args.hasFlag(options::OPT_fsplit_stack, options::OPT_fno_split_stack,
5166                    false))
5167     CmdArgs.push_back("-fsplit-stack");
5168 
5169   // -fprotect-parens=0 is default.
5170   if (Args.hasFlag(options::OPT_fprotect_parens,
5171                    options::OPT_fno_protect_parens, false))
5172     CmdArgs.push_back("-fprotect-parens");
5173 
5174   RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5175 
5176   if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5177     const llvm::Triple::ArchType Arch = TC.getArch();
5178     if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5179       StringRef V = A->getValue();
5180       if (V == "64")
5181         CmdArgs.push_back("-fextend-arguments=64");
5182       else if (V != "32")
5183         D.Diag(diag::err_drv_invalid_argument_to_option)
5184             << A->getValue() << A->getOption().getName();
5185     } else
5186       D.Diag(diag::err_drv_unsupported_opt_for_target)
5187           << A->getOption().getName() << TripleStr;
5188   }
5189 
5190   if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
5191     if (TC.getArch() == llvm::Triple::avr)
5192       A->render(Args, CmdArgs);
5193     else
5194       D.Diag(diag::err_drv_unsupported_opt_for_target)
5195           << A->getAsString(Args) << TripleStr;
5196   }
5197 
5198   if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5199     if (TC.getTriple().isX86())
5200       A->render(Args, CmdArgs);
5201     else if (TC.getTriple().isPPC() &&
5202              (A->getOption().getID() != options::OPT_mlong_double_80))
5203       A->render(Args, CmdArgs);
5204     else
5205       D.Diag(diag::err_drv_unsupported_opt_for_target)
5206           << A->getAsString(Args) << TripleStr;
5207   }
5208 
5209   // Decide whether to use verbose asm. Verbose assembly is the default on
5210   // toolchains which have the integrated assembler on by default.
5211   bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5212   if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5213                     IsIntegratedAssemblerDefault))
5214     CmdArgs.push_back("-fno-verbose-asm");
5215 
5216   // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5217   // use that to indicate the MC default in the backend.
5218   if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5219     StringRef V = A->getValue();
5220     unsigned Num;
5221     if (V == "none")
5222       A->render(Args, CmdArgs);
5223     else if (!V.consumeInteger(10, Num) && Num > 0 &&
5224              (V.empty() || (V.consume_front(".") &&
5225                             !V.consumeInteger(10, Num) && V.empty())))
5226       A->render(Args, CmdArgs);
5227     else
5228       D.Diag(diag::err_drv_invalid_argument_to_option)
5229           << A->getValue() << A->getOption().getName();
5230   }
5231 
5232   // If toolchain choose to use MCAsmParser for inline asm don't pass the
5233   // option to disable integrated-as explictly.
5234   if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5235     CmdArgs.push_back("-no-integrated-as");
5236 
5237   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
5238     CmdArgs.push_back("-mdebug-pass");
5239     CmdArgs.push_back("Structure");
5240   }
5241   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
5242     CmdArgs.push_back("-mdebug-pass");
5243     CmdArgs.push_back("Arguments");
5244   }
5245 
5246   // Enable -mconstructor-aliases except on darwin, where we have to work around
5247   // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
5248   // aliases aren't supported.
5249   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5250     CmdArgs.push_back("-mconstructor-aliases");
5251 
5252   // Darwin's kernel doesn't support guard variables; just die if we
5253   // try to use them.
5254   if (KernelOrKext && RawTriple.isOSDarwin())
5255     CmdArgs.push_back("-fforbid-guard-variables");
5256 
5257   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
5258                    Triple.isWindowsGNUEnvironment())) {
5259     CmdArgs.push_back("-mms-bitfields");
5260   }
5261 
5262   // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5263   // defaults to -fno-direct-access-external-data. Pass the option if different
5264   // from the default.
5265   if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
5266                                options::OPT_fno_direct_access_external_data))
5267     if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5268         (PICLevel == 0))
5269       A->render(Args, CmdArgs);
5270 
5271   if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
5272     CmdArgs.push_back("-fno-plt");
5273   }
5274 
5275   // -fhosted is default.
5276   // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5277   // use Freestanding.
5278   bool Freestanding =
5279       Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5280       KernelOrKext;
5281   if (Freestanding)
5282     CmdArgs.push_back("-ffreestanding");
5283 
5284   // This is a coarse approximation of what llvm-gcc actually does, both
5285   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
5286   // complicated ways.
5287   auto SanitizeArgs = TC.getSanitizerArgs(Args);
5288   bool AsyncUnwindTables = Args.hasFlag(
5289       options::OPT_fasynchronous_unwind_tables,
5290       options::OPT_fno_asynchronous_unwind_tables,
5291       (TC.IsUnwindTablesDefault(Args) || SanitizeArgs.needsUnwindTables()) &&
5292           !Freestanding);
5293   bool UnwindTables = Args.hasFlag(options::OPT_funwind_tables,
5294                                    options::OPT_fno_unwind_tables, false);
5295   if (AsyncUnwindTables)
5296     CmdArgs.push_back("-funwind-tables=2");
5297   else if (UnwindTables)
5298     CmdArgs.push_back("-funwind-tables=1");
5299 
5300   // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
5301   // `--gpu-use-aux-triple-only` is specified.
5302   if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5303       (IsCudaDevice || IsHIPDevice)) {
5304     const ArgList &HostArgs =
5305         C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
5306     std::string HostCPU =
5307         getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
5308     if (!HostCPU.empty()) {
5309       CmdArgs.push_back("-aux-target-cpu");
5310       CmdArgs.push_back(Args.MakeArgString(HostCPU));
5311     }
5312     getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
5313                       /*ForAS*/ false, /*IsAux*/ true);
5314   }
5315 
5316   TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5317 
5318   // FIXME: Handle -mtune=.
5319   (void)Args.hasArg(options::OPT_mtune_EQ);
5320 
5321   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
5322     StringRef CM = A->getValue();
5323     if (CM == "small" || CM == "kernel" || CM == "medium" || CM == "large" ||
5324         CM == "tiny") {
5325       if (Triple.isOSAIX() && CM == "medium")
5326         CmdArgs.push_back("-mcmodel=large");
5327       else
5328         A->render(Args, CmdArgs);
5329     } else {
5330       D.Diag(diag::err_drv_invalid_argument_to_option)
5331           << CM << A->getOption().getName();
5332     }
5333   }
5334 
5335   if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
5336     StringRef Value = A->getValue();
5337     unsigned TLSSize = 0;
5338     Value.getAsInteger(10, TLSSize);
5339     if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
5340       D.Diag(diag::err_drv_unsupported_opt_for_target)
5341           << A->getOption().getName() << TripleStr;
5342     if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
5343       D.Diag(diag::err_drv_invalid_int_value)
5344           << A->getOption().getName() << Value;
5345     Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
5346   }
5347 
5348   // Add the target cpu
5349   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
5350   if (!CPU.empty()) {
5351     CmdArgs.push_back("-target-cpu");
5352     CmdArgs.push_back(Args.MakeArgString(CPU));
5353   }
5354 
5355   RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
5356 
5357   // FIXME: For now we want to demote any errors to warnings, when they have
5358   // been raised for asking the wrong question of scalable vectors, such as
5359   // asking for the fixed number of elements. This may happen because code that
5360   // is not yet ported to work for scalable vectors uses the wrong interfaces,
5361   // whereas the behaviour is actually correct. Emitting a warning helps bring
5362   // up scalable vector support in an incremental way. When scalable vector
5363   // support is stable enough, all uses of wrong interfaces should be considered
5364   // as errors, but until then, we can live with a warning being emitted by the
5365   // compiler. This way, Clang can be used to compile code with scalable vectors
5366   // and identify possible issues.
5367   if (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5368       isa<BackendJobAction>(JA)) {
5369     CmdArgs.push_back("-mllvm");
5370     CmdArgs.push_back("-treat-scalable-fixed-error-as-warning");
5371   }
5372 
5373   // These two are potentially updated by AddClangCLArgs.
5374   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5375   bool EmitCodeView = false;
5376 
5377   // Add clang-cl arguments.
5378   types::ID InputType = Input.getType();
5379   if (D.IsCLMode())
5380     AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
5381 
5382   DwarfFissionKind DwarfFission = DwarfFissionKind::None;
5383   renderDebugOptions(TC, D, RawTriple, Args, EmitCodeView,
5384                      types::isLLVMIR(InputType), CmdArgs, DebugInfoKind,
5385                      DwarfFission);
5386 
5387   // This controls whether or not we perform JustMyCode instrumentation.
5388   if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
5389     if (TC.getTriple().isOSBinFormatELF()) {
5390       if (DebugInfoKind >= codegenoptions::DebugInfoConstructor)
5391         CmdArgs.push_back("-fjmc");
5392       else
5393         D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5394                                                              << "-g";
5395     } else {
5396       D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
5397     }
5398   }
5399 
5400   // Add the split debug info name to the command lines here so we
5401   // can propagate it to the backend.
5402   bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
5403                     (TC.getTriple().isOSBinFormatELF() ||
5404                      TC.getTriple().isOSBinFormatWasm()) &&
5405                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5406                      isa<BackendJobAction>(JA));
5407   if (SplitDWARF) {
5408     const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
5409     CmdArgs.push_back("-split-dwarf-file");
5410     CmdArgs.push_back(SplitDWARFOut);
5411     if (DwarfFission == DwarfFissionKind::Split) {
5412       CmdArgs.push_back("-split-dwarf-output");
5413       CmdArgs.push_back(SplitDWARFOut);
5414     }
5415   }
5416 
5417   // Pass the linker version in use.
5418   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
5419     CmdArgs.push_back("-target-linker-version");
5420     CmdArgs.push_back(A->getValue());
5421   }
5422 
5423   // Explicitly error on some things we know we don't support and can't just
5424   // ignore.
5425   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
5426     Arg *Unsupported;
5427     if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
5428         TC.getArch() == llvm::Triple::x86) {
5429       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
5430           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
5431         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
5432             << Unsupported->getOption().getName();
5433     }
5434     // The faltivec option has been superseded by the maltivec option.
5435     if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
5436       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5437           << Unsupported->getOption().getName()
5438           << "please use -maltivec and include altivec.h explicitly";
5439     if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
5440       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5441           << Unsupported->getOption().getName() << "please use -mno-altivec";
5442   }
5443 
5444   Args.AddAllArgs(CmdArgs, options::OPT_v);
5445 
5446   if (Args.getLastArg(options::OPT_H)) {
5447     CmdArgs.push_back("-H");
5448     CmdArgs.push_back("-sys-header-deps");
5449   }
5450   Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
5451 
5452   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
5453     CmdArgs.push_back("-header-include-file");
5454     CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
5455                           ? D.CCPrintHeadersFilename.c_str()
5456                           : "-");
5457     CmdArgs.push_back("-sys-header-deps");
5458   }
5459   Args.AddLastArg(CmdArgs, options::OPT_P);
5460   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
5461 
5462   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
5463     CmdArgs.push_back("-diagnostic-log-file");
5464     CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
5465                           ? D.CCLogDiagnosticsFilename.c_str()
5466                           : "-");
5467   }
5468 
5469   // Give the gen diagnostics more chances to succeed, by avoiding intentional
5470   // crashes.
5471   if (D.CCGenDiagnostics)
5472     CmdArgs.push_back("-disable-pragma-debug-crash");
5473 
5474   // Allow backend to put its diagnostic files in the same place as frontend
5475   // crash diagnostics files.
5476   if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
5477     StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
5478     CmdArgs.push_back("-mllvm");
5479     CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
5480   }
5481 
5482   bool UseSeparateSections = isUseSeparateSections(Triple);
5483 
5484   if (Args.hasFlag(options::OPT_ffunction_sections,
5485                    options::OPT_fno_function_sections, UseSeparateSections)) {
5486     CmdArgs.push_back("-ffunction-sections");
5487   }
5488 
5489   if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
5490     StringRef Val = A->getValue();
5491     if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5492       if (Val != "all" && Val != "labels" && Val != "none" &&
5493           !Val.startswith("list="))
5494         D.Diag(diag::err_drv_invalid_value)
5495             << A->getAsString(Args) << A->getValue();
5496       else
5497         A->render(Args, CmdArgs);
5498     } else if (Triple.isNVPTX()) {
5499       // Do not pass the option to the GPU compilation. We still want it enabled
5500       // for the host-side compilation, so seeing it here is not an error.
5501     } else if (Val != "none") {
5502       // =none is allowed everywhere. It's useful for overriding the option
5503       // and is the same as not specifying the option.
5504       D.Diag(diag::err_drv_unsupported_opt_for_target)
5505           << A->getAsString(Args) << TripleStr;
5506     }
5507   }
5508 
5509   bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
5510   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
5511                    UseSeparateSections || HasDefaultDataSections)) {
5512     CmdArgs.push_back("-fdata-sections");
5513   }
5514 
5515   Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
5516                      options::OPT_fno_unique_section_names);
5517   Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
5518                     options::OPT_fno_unique_internal_linkage_names);
5519   Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
5520                     options::OPT_fno_unique_basic_block_section_names);
5521 
5522   if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
5523                                options::OPT_fno_split_machine_functions)) {
5524     // This codegen pass is only available on x86-elf targets.
5525     if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5526       if (A->getOption().matches(options::OPT_fsplit_machine_functions))
5527         A->render(Args, CmdArgs);
5528     } else {
5529       D.Diag(diag::err_drv_unsupported_opt_for_target)
5530           << A->getAsString(Args) << TripleStr;
5531     }
5532   }
5533 
5534   Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
5535                   options::OPT_finstrument_functions_after_inlining,
5536                   options::OPT_finstrument_function_entry_bare);
5537 
5538   // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
5539   // for sampling, overhead of call arc collection is way too high and there's
5540   // no way to collect the output.
5541   if (!Triple.isNVPTX() && !Triple.isAMDGCN())
5542     addPGOAndCoverageFlags(TC, C, D, Output, Args, SanitizeArgs, CmdArgs);
5543 
5544   Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
5545 
5546   // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
5547   if (RawTriple.isPS() &&
5548       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
5549     PScpu::addProfileRTArgs(TC, Args, CmdArgs);
5550     PScpu::addSanitizerArgs(TC, Args, CmdArgs);
5551   }
5552 
5553   // Pass options for controlling the default header search paths.
5554   if (Args.hasArg(options::OPT_nostdinc)) {
5555     CmdArgs.push_back("-nostdsysteminc");
5556     CmdArgs.push_back("-nobuiltininc");
5557   } else {
5558     if (Args.hasArg(options::OPT_nostdlibinc))
5559       CmdArgs.push_back("-nostdsysteminc");
5560     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
5561     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
5562   }
5563 
5564   // Pass the path to compiler resource files.
5565   CmdArgs.push_back("-resource-dir");
5566   CmdArgs.push_back(D.ResourceDir.c_str());
5567 
5568   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
5569 
5570   RenderARCMigrateToolOptions(D, Args, CmdArgs);
5571 
5572   // Add preprocessing options like -I, -D, etc. if we are using the
5573   // preprocessor.
5574   //
5575   // FIXME: Support -fpreprocessed
5576   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
5577     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
5578 
5579   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
5580   // that "The compiler can only warn and ignore the option if not recognized".
5581   // When building with ccache, it will pass -D options to clang even on
5582   // preprocessed inputs and configure concludes that -fPIC is not supported.
5583   Args.ClaimAllArgs(options::OPT_D);
5584 
5585   // Manually translate -O4 to -O3; let clang reject others.
5586   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5587     if (A->getOption().matches(options::OPT_O4)) {
5588       CmdArgs.push_back("-O3");
5589       D.Diag(diag::warn_O4_is_O3);
5590     } else {
5591       A->render(Args, CmdArgs);
5592     }
5593   }
5594 
5595   // Warn about ignored options to clang.
5596   for (const Arg *A :
5597        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
5598     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
5599     A->claim();
5600   }
5601 
5602   for (const Arg *A :
5603        Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
5604     D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
5605     A->claim();
5606   }
5607 
5608   claimNoWarnArgs(Args);
5609 
5610   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
5611 
5612   for (const Arg *A :
5613        Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
5614     A->claim();
5615     if (A->getOption().getID() == options::OPT__SLASH_wd) {
5616       unsigned WarningNumber;
5617       if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
5618         D.Diag(diag::err_drv_invalid_int_value)
5619             << A->getAsString(Args) << A->getValue();
5620         continue;
5621       }
5622 
5623       if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
5624         CmdArgs.push_back(Args.MakeArgString(
5625             "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
5626       }
5627       continue;
5628     }
5629     A->render(Args, CmdArgs);
5630   }
5631 
5632   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
5633     CmdArgs.push_back("-pedantic");
5634   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
5635   Args.AddLastArg(CmdArgs, options::OPT_w);
5636 
5637   // Fixed point flags
5638   if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
5639                    /*Default=*/false))
5640     Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
5641 
5642   if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
5643     A->render(Args, CmdArgs);
5644 
5645   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5646                   options::OPT_fno_experimental_relative_cxx_abi_vtables);
5647 
5648   if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
5649     A->render(Args, CmdArgs);
5650 
5651   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
5652   // (-ansi is equivalent to -std=c89 or -std=c++98).
5653   //
5654   // If a std is supplied, only add -trigraphs if it follows the
5655   // option.
5656   bool ImplyVCPPCVer = false;
5657   bool ImplyVCPPCXXVer = false;
5658   const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
5659   if (Std) {
5660     if (Std->getOption().matches(options::OPT_ansi))
5661       if (types::isCXX(InputType))
5662         CmdArgs.push_back("-std=c++98");
5663       else
5664         CmdArgs.push_back("-std=c89");
5665     else
5666       Std->render(Args, CmdArgs);
5667 
5668     // If -f(no-)trigraphs appears after the language standard flag, honor it.
5669     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
5670                                  options::OPT_ftrigraphs,
5671                                  options::OPT_fno_trigraphs))
5672       if (A != Std)
5673         A->render(Args, CmdArgs);
5674   } else {
5675     // Honor -std-default.
5676     //
5677     // FIXME: Clang doesn't correctly handle -std= when the input language
5678     // doesn't match. For the time being just ignore this for C++ inputs;
5679     // eventually we want to do all the standard defaulting here instead of
5680     // splitting it between the driver and clang -cc1.
5681     if (!types::isCXX(InputType)) {
5682       if (!Args.hasArg(options::OPT__SLASH_std)) {
5683         Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
5684                                   /*Joined=*/true);
5685       } else
5686         ImplyVCPPCVer = true;
5687     }
5688     else if (IsWindowsMSVC)
5689       ImplyVCPPCXXVer = true;
5690 
5691     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
5692                     options::OPT_fno_trigraphs);
5693 
5694     // HIP headers has minimum C++ standard requirements. Therefore set the
5695     // default language standard.
5696     if (IsHIP)
5697       CmdArgs.push_back(IsWindowsMSVC ? "-std=c++14" : "-std=c++11");
5698   }
5699 
5700   // GCC's behavior for -Wwrite-strings is a bit strange:
5701   //  * In C, this "warning flag" changes the types of string literals from
5702   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
5703   //    for the discarded qualifier.
5704   //  * In C++, this is just a normal warning flag.
5705   //
5706   // Implementing this warning correctly in C is hard, so we follow GCC's
5707   // behavior for now. FIXME: Directly diagnose uses of a string literal as
5708   // a non-const char* in C, rather than using this crude hack.
5709   if (!types::isCXX(InputType)) {
5710     // FIXME: This should behave just like a warning flag, and thus should also
5711     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
5712     Arg *WriteStrings =
5713         Args.getLastArg(options::OPT_Wwrite_strings,
5714                         options::OPT_Wno_write_strings, options::OPT_w);
5715     if (WriteStrings &&
5716         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
5717       CmdArgs.push_back("-fconst-strings");
5718   }
5719 
5720   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
5721   // during C++ compilation, which it is by default. GCC keeps this define even
5722   // in the presence of '-w', match this behavior bug-for-bug.
5723   if (types::isCXX(InputType) &&
5724       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
5725                    true)) {
5726     CmdArgs.push_back("-fdeprecated-macro");
5727   }
5728 
5729   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
5730   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
5731     if (Asm->getOption().matches(options::OPT_fasm))
5732       CmdArgs.push_back("-fgnu-keywords");
5733     else
5734       CmdArgs.push_back("-fno-gnu-keywords");
5735   }
5736 
5737   if (!ShouldEnableAutolink(Args, TC, JA))
5738     CmdArgs.push_back("-fno-autolink");
5739 
5740   // Add in -fdebug-compilation-dir if necessary.
5741   const char *DebugCompilationDir =
5742       addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5743 
5744   addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5745 
5746   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
5747                                options::OPT_ftemplate_depth_EQ)) {
5748     CmdArgs.push_back("-ftemplate-depth");
5749     CmdArgs.push_back(A->getValue());
5750   }
5751 
5752   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
5753     CmdArgs.push_back("-foperator-arrow-depth");
5754     CmdArgs.push_back(A->getValue());
5755   }
5756 
5757   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
5758     CmdArgs.push_back("-fconstexpr-depth");
5759     CmdArgs.push_back(A->getValue());
5760   }
5761 
5762   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
5763     CmdArgs.push_back("-fconstexpr-steps");
5764     CmdArgs.push_back(A->getValue());
5765   }
5766 
5767   if (Args.hasArg(options::OPT_funstable)) {
5768     CmdArgs.push_back("-funstable");
5769     if (!Args.hasArg(options::OPT_fno_coroutines_ts))
5770       CmdArgs.push_back("-fcoroutines-ts");
5771     CmdArgs.push_back("-fmodules-ts");
5772   }
5773 
5774   if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
5775     CmdArgs.push_back("-fexperimental-new-constant-interpreter");
5776 
5777   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
5778     CmdArgs.push_back("-fbracket-depth");
5779     CmdArgs.push_back(A->getValue());
5780   }
5781 
5782   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
5783                                options::OPT_Wlarge_by_value_copy_def)) {
5784     if (A->getNumValues()) {
5785       StringRef bytes = A->getValue();
5786       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
5787     } else
5788       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
5789   }
5790 
5791   if (Args.hasArg(options::OPT_relocatable_pch))
5792     CmdArgs.push_back("-relocatable-pch");
5793 
5794   if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
5795     static const char *kCFABIs[] = {
5796       "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
5797     };
5798 
5799     if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
5800       D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
5801     else
5802       A->render(Args, CmdArgs);
5803   }
5804 
5805   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
5806     CmdArgs.push_back("-fconstant-string-class");
5807     CmdArgs.push_back(A->getValue());
5808   }
5809 
5810   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
5811     CmdArgs.push_back("-ftabstop");
5812     CmdArgs.push_back(A->getValue());
5813   }
5814 
5815   if (Args.hasFlag(options::OPT_fstack_size_section,
5816                    options::OPT_fno_stack_size_section, RawTriple.isPS4()))
5817     CmdArgs.push_back("-fstack-size-section");
5818 
5819   if (Args.hasArg(options::OPT_fstack_usage)) {
5820     CmdArgs.push_back("-stack-usage-file");
5821 
5822     if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5823       SmallString<128> OutputFilename(OutputOpt->getValue());
5824       llvm::sys::path::replace_extension(OutputFilename, "su");
5825       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
5826     } else
5827       CmdArgs.push_back(
5828           Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
5829   }
5830 
5831   CmdArgs.push_back("-ferror-limit");
5832   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
5833     CmdArgs.push_back(A->getValue());
5834   else
5835     CmdArgs.push_back("19");
5836 
5837   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
5838     CmdArgs.push_back("-fmacro-backtrace-limit");
5839     CmdArgs.push_back(A->getValue());
5840   }
5841 
5842   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
5843     CmdArgs.push_back("-ftemplate-backtrace-limit");
5844     CmdArgs.push_back(A->getValue());
5845   }
5846 
5847   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
5848     CmdArgs.push_back("-fconstexpr-backtrace-limit");
5849     CmdArgs.push_back(A->getValue());
5850   }
5851 
5852   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
5853     CmdArgs.push_back("-fspell-checking-limit");
5854     CmdArgs.push_back(A->getValue());
5855   }
5856 
5857   // Pass -fmessage-length=.
5858   unsigned MessageLength = 0;
5859   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
5860     StringRef V(A->getValue());
5861     if (V.getAsInteger(0, MessageLength))
5862       D.Diag(diag::err_drv_invalid_argument_to_option)
5863           << V << A->getOption().getName();
5864   } else {
5865     // If -fmessage-length=N was not specified, determine whether this is a
5866     // terminal and, if so, implicitly define -fmessage-length appropriately.
5867     MessageLength = llvm::sys::Process::StandardErrColumns();
5868   }
5869   if (MessageLength != 0)
5870     CmdArgs.push_back(
5871         Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
5872 
5873   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
5874     CmdArgs.push_back(
5875         Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
5876 
5877   if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
5878     CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
5879                                          Twine(A->getValue(0))));
5880 
5881   // -fvisibility= and -fvisibility-ms-compat are of a piece.
5882   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
5883                                      options::OPT_fvisibility_ms_compat)) {
5884     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
5885       CmdArgs.push_back("-fvisibility");
5886       CmdArgs.push_back(A->getValue());
5887     } else {
5888       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
5889       CmdArgs.push_back("-fvisibility");
5890       CmdArgs.push_back("hidden");
5891       CmdArgs.push_back("-ftype-visibility");
5892       CmdArgs.push_back("default");
5893     }
5894   } else if (IsOpenMPDevice) {
5895     // When compiling for the OpenMP device we want protected visibility by
5896     // default. This prevents the device from accidenally preempting code on the
5897     // host, makes the system more robust, and improves performance.
5898     CmdArgs.push_back("-fvisibility");
5899     CmdArgs.push_back("protected");
5900   }
5901 
5902   if (!RawTriple.isPS4())
5903     if (const Arg *A =
5904             Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
5905                             options::OPT_fno_visibility_from_dllstorageclass)) {
5906       if (A->getOption().matches(
5907               options::OPT_fvisibility_from_dllstorageclass)) {
5908         CmdArgs.push_back("-fvisibility-from-dllstorageclass");
5909         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
5910         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
5911         Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
5912         Args.AddLastArg(CmdArgs,
5913                         options::OPT_fvisibility_externs_nodllstorageclass_EQ);
5914       }
5915     }
5916 
5917   if (const Arg *A = Args.getLastArg(options::OPT_mignore_xcoff_visibility)) {
5918     if (Triple.isOSAIX())
5919       CmdArgs.push_back("-mignore-xcoff-visibility");
5920     else
5921       D.Diag(diag::err_drv_unsupported_opt_for_target)
5922           << A->getAsString(Args) << TripleStr;
5923   }
5924 
5925 
5926   if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
5927                     options::OPT_fno_visibility_inlines_hidden, false))
5928     CmdArgs.push_back("-fvisibility-inlines-hidden");
5929 
5930   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
5931                            options::OPT_fno_visibility_inlines_hidden_static_local_var);
5932   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
5933   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
5934 
5935   if (Args.hasFlag(options::OPT_fnew_infallible,
5936                    options::OPT_fno_new_infallible, false))
5937     CmdArgs.push_back("-fnew-infallible");
5938 
5939   if (Args.hasFlag(options::OPT_fno_operator_names,
5940                    options::OPT_foperator_names, false))
5941     CmdArgs.push_back("-fno-operator-names");
5942 
5943   // Forward -f (flag) options which we can pass directly.
5944   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
5945   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
5946   Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
5947   Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
5948                   options::OPT_fno_emulated_tls);
5949   Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
5950 
5951   if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
5952     // FIXME: There's no reason for this to be restricted to X86. The backend
5953     // code needs to be changed to include the appropriate function calls
5954     // automatically.
5955     if (!Triple.isX86())
5956       D.Diag(diag::err_drv_unsupported_opt_for_target)
5957           << A->getAsString(Args) << TripleStr;
5958   }
5959 
5960   // AltiVec-like language extensions aren't relevant for assembling.
5961   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
5962     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
5963 
5964   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
5965   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
5966 
5967   // Forward flags for OpenMP. We don't do this if the current action is an
5968   // device offloading action other than OpenMP.
5969   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
5970                    options::OPT_fno_openmp, false) &&
5971       (JA.isDeviceOffloading(Action::OFK_None) ||
5972        JA.isDeviceOffloading(Action::OFK_OpenMP))) {
5973     switch (D.getOpenMPRuntime(Args)) {
5974     case Driver::OMPRT_OMP:
5975     case Driver::OMPRT_IOMP5:
5976       // Clang can generate useful OpenMP code for these two runtime libraries.
5977       CmdArgs.push_back("-fopenmp");
5978 
5979       // If no option regarding the use of TLS in OpenMP codegeneration is
5980       // given, decide a default based on the target. Otherwise rely on the
5981       // options and pass the right information to the frontend.
5982       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
5983                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
5984         CmdArgs.push_back("-fnoopenmp-use-tls");
5985       Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
5986                       options::OPT_fno_openmp_simd);
5987       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
5988       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
5989       if (!Args.hasFlag(options::OPT_fopenmp_extensions,
5990                         options::OPT_fno_openmp_extensions, /*Default=*/true))
5991         CmdArgs.push_back("-fno-openmp-extensions");
5992       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
5993       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
5994       Args.AddAllArgs(CmdArgs,
5995                       options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
5996       if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
5997                        options::OPT_fno_openmp_optimistic_collapse,
5998                        /*Default=*/false))
5999         CmdArgs.push_back("-fopenmp-optimistic-collapse");
6000 
6001       // When in OpenMP offloading mode with NVPTX target, forward
6002       // cuda-mode flag
6003       if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
6004                        options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6005         CmdArgs.push_back("-fopenmp-cuda-mode");
6006 
6007       // When in OpenMP offloading mode, enable debugging on the device.
6008       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6009       if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6010                        options::OPT_fno_openmp_target_debug, /*Default=*/false))
6011         CmdArgs.push_back("-fopenmp-target-debug");
6012 
6013       // When in OpenMP offloading mode with NVPTX target, check if full runtime
6014       // is required.
6015       if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
6016                        options::OPT_fno_openmp_cuda_force_full_runtime,
6017                        /*Default=*/false))
6018         CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
6019 
6020       // When in OpenMP offloading mode, forward assumptions information about
6021       // thread and team counts in the device.
6022       if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6023                        options::OPT_fno_openmp_assume_teams_oversubscription,
6024                        /*Default=*/false))
6025         CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
6026       if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6027                        options::OPT_fno_openmp_assume_threads_oversubscription,
6028                        /*Default=*/false))
6029         CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
6030       if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
6031         CmdArgs.push_back("-fopenmp-assume-no-thread-state");
6032       if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
6033         CmdArgs.push_back("-fopenmp-offload-mandatory");
6034       break;
6035     default:
6036       // By default, if Clang doesn't know how to generate useful OpenMP code
6037       // for a specific runtime library, we just don't pass the '-fopenmp' flag
6038       // down to the actual compilation.
6039       // FIXME: It would be better to have a mode which *only* omits IR
6040       // generation based on the OpenMP support so that we get consistent
6041       // semantic analysis, etc.
6042       break;
6043     }
6044   } else {
6045     Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6046                     options::OPT_fno_openmp_simd);
6047     Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6048     Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
6049                        options::OPT_fno_openmp_extensions);
6050   }
6051 
6052   SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
6053 
6054   const XRayArgs &XRay = TC.getXRayArgs();
6055   XRay.addArgs(TC, Args, CmdArgs, InputType);
6056 
6057   for (const auto &Filename :
6058        Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6059     if (D.getVFS().exists(Filename))
6060       CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6061     else
6062       D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6063   }
6064 
6065   if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6066     StringRef S0 = A->getValue(), S = S0;
6067     unsigned Size, Offset = 0;
6068     if (!Triple.isAArch64() && !Triple.isRISCV() && !Triple.isX86())
6069       D.Diag(diag::err_drv_unsupported_opt_for_target)
6070           << A->getAsString(Args) << TripleStr;
6071     else if (S.consumeInteger(10, Size) ||
6072              (!S.empty() && (!S.consume_front(",") ||
6073                              S.consumeInteger(10, Offset) || !S.empty())))
6074       D.Diag(diag::err_drv_invalid_argument_to_option)
6075           << S0 << A->getOption().getName();
6076     else if (Size < Offset)
6077       D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
6078     else {
6079       CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
6080       CmdArgs.push_back(Args.MakeArgString(
6081           "-fpatchable-function-entry-offset=" + Twine(Offset)));
6082     }
6083   }
6084 
6085   Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
6086 
6087   if (TC.SupportsProfiling()) {
6088     Args.AddLastArg(CmdArgs, options::OPT_pg);
6089 
6090     llvm::Triple::ArchType Arch = TC.getArch();
6091     if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
6092       if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6093         A->render(Args, CmdArgs);
6094       else
6095         D.Diag(diag::err_drv_unsupported_opt_for_target)
6096             << A->getAsString(Args) << TripleStr;
6097     }
6098     if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
6099       if (Arch == llvm::Triple::systemz)
6100         A->render(Args, CmdArgs);
6101       else
6102         D.Diag(diag::err_drv_unsupported_opt_for_target)
6103             << A->getAsString(Args) << TripleStr;
6104     }
6105     if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
6106       if (Arch == llvm::Triple::systemz)
6107         A->render(Args, CmdArgs);
6108       else
6109         D.Diag(diag::err_drv_unsupported_opt_for_target)
6110             << A->getAsString(Args) << TripleStr;
6111     }
6112   }
6113 
6114   if (Args.getLastArg(options::OPT_fapple_kext) ||
6115       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
6116     CmdArgs.push_back("-fapple-kext");
6117 
6118   Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
6119   Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
6120   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
6121   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
6122   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
6123   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
6124   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
6125   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
6126   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
6127   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
6128   Args.AddLastArg(CmdArgs, options::OPT_malign_double);
6129   Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
6130 
6131   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
6132     CmdArgs.push_back("-ftrapv-handler");
6133     CmdArgs.push_back(A->getValue());
6134   }
6135 
6136   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
6137 
6138   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
6139   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
6140   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
6141     if (A->getOption().matches(options::OPT_fwrapv))
6142       CmdArgs.push_back("-fwrapv");
6143   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
6144                                       options::OPT_fno_strict_overflow)) {
6145     if (A->getOption().matches(options::OPT_fno_strict_overflow))
6146       CmdArgs.push_back("-fwrapv");
6147   }
6148 
6149   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
6150                                options::OPT_fno_reroll_loops))
6151     if (A->getOption().matches(options::OPT_freroll_loops))
6152       CmdArgs.push_back("-freroll-loops");
6153 
6154   Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
6155                   options::OPT_fno_finite_loops);
6156 
6157   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
6158   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
6159                   options::OPT_fno_unroll_loops);
6160 
6161   Args.AddLastArg(CmdArgs, options::OPT_pthread);
6162 
6163   if (Args.hasFlag(options::OPT_mspeculative_load_hardening,
6164                    options::OPT_mno_speculative_load_hardening, false))
6165     CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
6166 
6167   RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
6168   RenderSCPOptions(TC, Args, CmdArgs);
6169   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
6170 
6171   Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
6172 
6173   // Translate -mstackrealign
6174   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
6175                    false))
6176     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
6177 
6178   if (Args.hasArg(options::OPT_mstack_alignment)) {
6179     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
6180     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
6181   }
6182 
6183   if (Args.hasArg(options::OPT_mstack_probe_size)) {
6184     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
6185 
6186     if (!Size.empty())
6187       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
6188     else
6189       CmdArgs.push_back("-mstack-probe-size=0");
6190   }
6191 
6192   Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
6193                      options::OPT_mno_stack_arg_probe);
6194 
6195   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
6196                                options::OPT_mno_restrict_it)) {
6197     if (A->getOption().matches(options::OPT_mrestrict_it)) {
6198       CmdArgs.push_back("-mllvm");
6199       CmdArgs.push_back("-arm-restrict-it");
6200     } else {
6201       CmdArgs.push_back("-mllvm");
6202       CmdArgs.push_back("-arm-default-it");
6203     }
6204   }
6205 
6206   // Forward -cl options to -cc1
6207   RenderOpenCLOptions(Args, CmdArgs, InputType);
6208 
6209   if (IsHIP) {
6210     if (Args.hasFlag(options::OPT_fhip_new_launch_api,
6211                      options::OPT_fno_hip_new_launch_api, true))
6212       CmdArgs.push_back("-fhip-new-launch-api");
6213     if (Args.hasFlag(options::OPT_fgpu_allow_device_init,
6214                      options::OPT_fno_gpu_allow_device_init, false))
6215       CmdArgs.push_back("-fgpu-allow-device-init");
6216   }
6217 
6218   if (IsCuda || IsHIP) {
6219     if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
6220       CmdArgs.push_back("-fgpu-rdc");
6221     if (Args.hasFlag(options::OPT_fgpu_defer_diag,
6222                      options::OPT_fno_gpu_defer_diag, false))
6223       CmdArgs.push_back("-fgpu-defer-diag");
6224     if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
6225                      options::OPT_fno_gpu_exclude_wrong_side_overloads,
6226                      false)) {
6227       CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
6228       CmdArgs.push_back("-fgpu-defer-diag");
6229     }
6230   }
6231 
6232   if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
6233     CmdArgs.push_back(
6234         Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
6235   }
6236 
6237   if (IsUsingLTO)
6238     Args.AddLastArg(CmdArgs, options::OPT_mibt_seal);
6239 
6240   // Forward -f options with positive and negative forms; we translate these by
6241   // hand.  Do not propagate PGO options to the GPU-side compilations as the
6242   // profile info is for the host-side compilation only.
6243   if (!(IsCudaDevice || IsHIPDevice)) {
6244     if (Arg *A = getLastProfileSampleUseArg(Args)) {
6245       auto *PGOArg = Args.getLastArg(
6246           options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
6247           options::OPT_fcs_profile_generate,
6248           options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
6249           options::OPT_fprofile_use_EQ);
6250       if (PGOArg)
6251         D.Diag(diag::err_drv_argument_not_allowed_with)
6252             << "SampleUse with PGO options";
6253 
6254       StringRef fname = A->getValue();
6255       if (!llvm::sys::fs::exists(fname))
6256         D.Diag(diag::err_drv_no_such_file) << fname;
6257       else
6258         A->render(Args, CmdArgs);
6259     }
6260     Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
6261 
6262     if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
6263                      options::OPT_fno_pseudo_probe_for_profiling, false)) {
6264       CmdArgs.push_back("-fpseudo-probe-for-profiling");
6265       // Enforce -funique-internal-linkage-names if it's not explicitly turned
6266       // off.
6267       if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
6268                        options::OPT_fno_unique_internal_linkage_names, true))
6269         CmdArgs.push_back("-funique-internal-linkage-names");
6270     }
6271   }
6272   RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
6273 
6274   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
6275                      options::OPT_fno_assume_sane_operator_new);
6276 
6277   // -fblocks=0 is default.
6278   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
6279                    TC.IsBlocksDefault()) ||
6280       (Args.hasArg(options::OPT_fgnu_runtime) &&
6281        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
6282        !Args.hasArg(options::OPT_fno_blocks))) {
6283     CmdArgs.push_back("-fblocks");
6284 
6285     if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
6286       CmdArgs.push_back("-fblocks-runtime-optional");
6287   }
6288 
6289   // -fencode-extended-block-signature=1 is default.
6290   if (TC.IsEncodeExtendedBlockSignatureDefault())
6291     CmdArgs.push_back("-fencode-extended-block-signature");
6292 
6293   if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
6294                    false) &&
6295       types::isCXX(InputType)) {
6296     CmdArgs.push_back("-fcoroutines-ts");
6297   }
6298 
6299   Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
6300                   options::OPT_fno_double_square_bracket_attributes);
6301 
6302   Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
6303                      options::OPT_fno_access_control);
6304   Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
6305                      options::OPT_fno_elide_constructors);
6306 
6307   ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
6308 
6309   if (KernelOrKext || (types::isCXX(InputType) &&
6310                        (RTTIMode == ToolChain::RM_Disabled)))
6311     CmdArgs.push_back("-fno-rtti");
6312 
6313   // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
6314   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
6315                    TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
6316     CmdArgs.push_back("-fshort-enums");
6317 
6318   RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
6319 
6320   // -fuse-cxa-atexit is default.
6321   if (!Args.hasFlag(
6322           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
6323           !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
6324               ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
6325                RawTriple.hasEnvironment())) ||
6326       KernelOrKext)
6327     CmdArgs.push_back("-fno-use-cxa-atexit");
6328 
6329   if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
6330                    options::OPT_fno_register_global_dtors_with_atexit,
6331                    RawTriple.isOSDarwin() && !KernelOrKext))
6332     CmdArgs.push_back("-fregister-global-dtors-with-atexit");
6333 
6334   Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
6335                     options::OPT_fno_use_line_directives);
6336 
6337   // -fno-minimize-whitespace is default.
6338   if (Args.hasFlag(options::OPT_fminimize_whitespace,
6339                    options::OPT_fno_minimize_whitespace, false)) {
6340     types::ID InputType = Inputs[0].getType();
6341     if (!isDerivedFromC(InputType))
6342       D.Diag(diag::err_drv_minws_unsupported_input_type)
6343           << types::getTypeName(InputType);
6344     CmdArgs.push_back("-fminimize-whitespace");
6345   }
6346 
6347   // -fms-extensions=0 is default.
6348   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
6349                    IsWindowsMSVC))
6350     CmdArgs.push_back("-fms-extensions");
6351 
6352   // -fms-compatibility=0 is default.
6353   bool IsMSVCCompat = Args.hasFlag(
6354       options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
6355       (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
6356                                      options::OPT_fno_ms_extensions, true)));
6357   if (IsMSVCCompat)
6358     CmdArgs.push_back("-fms-compatibility");
6359 
6360   // Handle -fgcc-version, if present.
6361   VersionTuple GNUCVer;
6362   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
6363     // Check that the version has 1 to 3 components and the minor and patch
6364     // versions fit in two decimal digits.
6365     StringRef Val = A->getValue();
6366     Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
6367     bool Invalid = GNUCVer.tryParse(Val);
6368     unsigned Minor = GNUCVer.getMinor().getValueOr(0);
6369     unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
6370     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
6371       D.Diag(diag::err_drv_invalid_value)
6372           << A->getAsString(Args) << A->getValue();
6373     }
6374   } else if (!IsMSVCCompat) {
6375     // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
6376     GNUCVer = VersionTuple(4, 2, 1);
6377   }
6378   if (!GNUCVer.empty()) {
6379     CmdArgs.push_back(
6380         Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
6381   }
6382 
6383   VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
6384   if (!MSVT.empty())
6385     CmdArgs.push_back(
6386         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
6387 
6388   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
6389   if (ImplyVCPPCVer) {
6390     StringRef LanguageStandard;
6391     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6392       Std = StdArg;
6393       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6394                              .Case("c11", "-std=c11")
6395                              .Case("c17", "-std=c17")
6396                              .Default("");
6397       if (LanguageStandard.empty())
6398         D.Diag(clang::diag::warn_drv_unused_argument)
6399             << StdArg->getAsString(Args);
6400     }
6401     CmdArgs.push_back(LanguageStandard.data());
6402   }
6403   if (ImplyVCPPCXXVer) {
6404     StringRef LanguageStandard;
6405     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6406       Std = StdArg;
6407       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6408                              .Case("c++14", "-std=c++14")
6409                              .Case("c++17", "-std=c++17")
6410                              .Case("c++20", "-std=c++20")
6411                              .Case("c++latest", "-std=c++2b")
6412                              .Default("");
6413       if (LanguageStandard.empty())
6414         D.Diag(clang::diag::warn_drv_unused_argument)
6415             << StdArg->getAsString(Args);
6416     }
6417 
6418     if (LanguageStandard.empty()) {
6419       if (IsMSVC2015Compatible)
6420         LanguageStandard = "-std=c++14";
6421       else
6422         LanguageStandard = "-std=c++11";
6423     }
6424 
6425     CmdArgs.push_back(LanguageStandard.data());
6426   }
6427 
6428   Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
6429                     options::OPT_fno_borland_extensions);
6430 
6431   // -fno-declspec is default, except for PS4.
6432   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
6433                    RawTriple.isPS4()))
6434     CmdArgs.push_back("-fdeclspec");
6435   else if (Args.hasArg(options::OPT_fno_declspec))
6436     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
6437 
6438   // -fthreadsafe-static is default, except for MSVC compatibility versions less
6439   // than 19.
6440   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
6441                     options::OPT_fno_threadsafe_statics,
6442                     !types::isOpenCL(InputType) &&
6443                         (!IsWindowsMSVC || IsMSVC2015Compatible)))
6444     CmdArgs.push_back("-fno-threadsafe-statics");
6445 
6446   // -fno-delayed-template-parsing is default, except when targeting MSVC.
6447   // Many old Windows SDK versions require this to parse.
6448   // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
6449   // compiler. We should be able to disable this by default at some point.
6450   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
6451                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
6452     CmdArgs.push_back("-fdelayed-template-parsing");
6453 
6454   // -fgnu-keywords default varies depending on language; only pass if
6455   // specified.
6456   Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
6457                   options::OPT_fno_gnu_keywords);
6458 
6459   Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
6460                     options::OPT_fno_gnu89_inline);
6461 
6462   const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
6463                                          options::OPT_finline_hint_functions,
6464                                          options::OPT_fno_inline_functions);
6465   if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
6466     if (A->getOption().matches(options::OPT_fno_inline))
6467       A->render(Args, CmdArgs);
6468   } else if (InlineArg) {
6469     InlineArg->render(Args, CmdArgs);
6470   }
6471 
6472   // FIXME: Find a better way to determine whether the language has modules
6473   // support by default, or just assume that all languages do.
6474   bool HaveModules =
6475       Std && (Std->containsValue("c++2a") || Std->containsValue("c++20") ||
6476               Std->containsValue("c++latest"));
6477   RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
6478 
6479   if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
6480                    options::OPT_fno_pch_validate_input_files_content, false))
6481     CmdArgs.push_back("-fvalidate-ast-input-files-content");
6482   if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
6483                    options::OPT_fno_pch_instantiate_templates, false))
6484     CmdArgs.push_back("-fpch-instantiate-templates");
6485   if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
6486                    false))
6487     CmdArgs.push_back("-fmodules-codegen");
6488   if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
6489                    false))
6490     CmdArgs.push_back("-fmodules-debuginfo");
6491 
6492   if (!CLANG_ENABLE_OPAQUE_POINTERS_INTERNAL)
6493     CmdArgs.push_back("-no-opaque-pointers");
6494 
6495   ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
6496   RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
6497                     Input, CmdArgs);
6498 
6499   if (types::isObjC(Input.getType()) &&
6500       Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
6501                    options::OPT_fno_objc_encode_cxx_class_template_spec,
6502                    !Runtime.isNeXTFamily()))
6503     CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
6504 
6505   if (Args.hasFlag(options::OPT_fapplication_extension,
6506                    options::OPT_fno_application_extension, false))
6507     CmdArgs.push_back("-fapplication-extension");
6508 
6509   // Handle GCC-style exception args.
6510   bool EH = false;
6511   if (!C.getDriver().IsCLMode())
6512     EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
6513 
6514   // Handle exception personalities
6515   Arg *A = Args.getLastArg(
6516       options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
6517       options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
6518   if (A) {
6519     const Option &Opt = A->getOption();
6520     if (Opt.matches(options::OPT_fsjlj_exceptions))
6521       CmdArgs.push_back("-exception-model=sjlj");
6522     if (Opt.matches(options::OPT_fseh_exceptions))
6523       CmdArgs.push_back("-exception-model=seh");
6524     if (Opt.matches(options::OPT_fdwarf_exceptions))
6525       CmdArgs.push_back("-exception-model=dwarf");
6526     if (Opt.matches(options::OPT_fwasm_exceptions))
6527       CmdArgs.push_back("-exception-model=wasm");
6528   } else {
6529     switch (TC.GetExceptionModel(Args)) {
6530     default:
6531       break;
6532     case llvm::ExceptionHandling::DwarfCFI:
6533       CmdArgs.push_back("-exception-model=dwarf");
6534       break;
6535     case llvm::ExceptionHandling::SjLj:
6536       CmdArgs.push_back("-exception-model=sjlj");
6537       break;
6538     case llvm::ExceptionHandling::WinEH:
6539       CmdArgs.push_back("-exception-model=seh");
6540       break;
6541     }
6542   }
6543 
6544   // C++ "sane" operator new.
6545   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
6546                      options::OPT_fno_assume_sane_operator_new);
6547 
6548   // -frelaxed-template-template-args is off by default, as it is a severe
6549   // breaking change until a corresponding change to template partial ordering
6550   // is provided.
6551   Args.addOptInFlag(CmdArgs, options::OPT_frelaxed_template_template_args,
6552                     options::OPT_fno_relaxed_template_template_args);
6553 
6554   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
6555   // most platforms.
6556   Args.addOptInFlag(CmdArgs, options::OPT_fsized_deallocation,
6557                     options::OPT_fno_sized_deallocation);
6558 
6559   // -faligned-allocation is on by default in C++17 onwards and otherwise off
6560   // by default.
6561   if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
6562                                options::OPT_fno_aligned_allocation,
6563                                options::OPT_faligned_new_EQ)) {
6564     if (A->getOption().matches(options::OPT_fno_aligned_allocation))
6565       CmdArgs.push_back("-fno-aligned-allocation");
6566     else
6567       CmdArgs.push_back("-faligned-allocation");
6568   }
6569 
6570   // The default new alignment can be specified using a dedicated option or via
6571   // a GCC-compatible option that also turns on aligned allocation.
6572   if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
6573                                options::OPT_faligned_new_EQ))
6574     CmdArgs.push_back(
6575         Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
6576 
6577   // -fconstant-cfstrings is default, and may be subject to argument translation
6578   // on Darwin.
6579   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
6580                     options::OPT_fno_constant_cfstrings, true) ||
6581       !Args.hasFlag(options::OPT_mconstant_cfstrings,
6582                     options::OPT_mno_constant_cfstrings, true))
6583     CmdArgs.push_back("-fno-constant-cfstrings");
6584 
6585   Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
6586                     options::OPT_fno_pascal_strings);
6587 
6588   // Honor -fpack-struct= and -fpack-struct, if given. Note that
6589   // -fno-pack-struct doesn't apply to -fpack-struct=.
6590   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
6591     std::string PackStructStr = "-fpack-struct=";
6592     PackStructStr += A->getValue();
6593     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
6594   } else if (Args.hasFlag(options::OPT_fpack_struct,
6595                           options::OPT_fno_pack_struct, false)) {
6596     CmdArgs.push_back("-fpack-struct=1");
6597   }
6598 
6599   // Handle -fmax-type-align=N and -fno-type-align
6600   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
6601   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
6602     if (!SkipMaxTypeAlign) {
6603       std::string MaxTypeAlignStr = "-fmax-type-align=";
6604       MaxTypeAlignStr += A->getValue();
6605       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6606     }
6607   } else if (RawTriple.isOSDarwin()) {
6608     if (!SkipMaxTypeAlign) {
6609       std::string MaxTypeAlignStr = "-fmax-type-align=16";
6610       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6611     }
6612   }
6613 
6614   if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
6615     CmdArgs.push_back("-Qn");
6616 
6617   // -fno-common is the default, set -fcommon only when that flag is set.
6618   Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
6619 
6620   // -fsigned-bitfields is default, and clang doesn't yet support
6621   // -funsigned-bitfields.
6622   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
6623                     options::OPT_funsigned_bitfields, true))
6624     D.Diag(diag::warn_drv_clang_unsupported)
6625         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
6626 
6627   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
6628   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
6629     D.Diag(diag::err_drv_clang_unsupported)
6630         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
6631 
6632   // -finput_charset=UTF-8 is default. Reject others
6633   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
6634     StringRef value = inputCharset->getValue();
6635     if (!value.equals_insensitive("utf-8"))
6636       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
6637                                           << value;
6638   }
6639 
6640   // -fexec_charset=UTF-8 is default. Reject others
6641   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
6642     StringRef value = execCharset->getValue();
6643     if (!value.equals_insensitive("utf-8"))
6644       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
6645                                           << value;
6646   }
6647 
6648   RenderDiagnosticsOptions(D, Args, CmdArgs);
6649 
6650   Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
6651                     options::OPT_fno_asm_blocks);
6652 
6653   // -fgnu-inline-asm is default.
6654   if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
6655                     options::OPT_fno_gnu_inline_asm, true))
6656     CmdArgs.push_back("-fno-gnu-inline-asm");
6657 
6658   // Enable vectorization per default according to the optimization level
6659   // selected. For optimization levels that want vectorization we use the alias
6660   // option to simplify the hasFlag logic.
6661   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
6662   OptSpecifier VectorizeAliasOption =
6663       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
6664   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
6665                    options::OPT_fno_vectorize, EnableVec))
6666     CmdArgs.push_back("-vectorize-loops");
6667 
6668   // -fslp-vectorize is enabled based on the optimization level selected.
6669   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
6670   OptSpecifier SLPVectAliasOption =
6671       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
6672   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
6673                    options::OPT_fno_slp_vectorize, EnableSLPVec))
6674     CmdArgs.push_back("-vectorize-slp");
6675 
6676   ParseMPreferVectorWidth(D, Args, CmdArgs);
6677 
6678   Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
6679   Args.AddLastArg(CmdArgs,
6680                   options::OPT_fsanitize_undefined_strip_path_components_EQ);
6681 
6682   // -fdollars-in-identifiers default varies depending on platform and
6683   // language; only pass if specified.
6684   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
6685                                options::OPT_fno_dollars_in_identifiers)) {
6686     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
6687       CmdArgs.push_back("-fdollars-in-identifiers");
6688     else
6689       CmdArgs.push_back("-fno-dollars-in-identifiers");
6690   }
6691 
6692   Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
6693                     options::OPT_fno_apple_pragma_pack);
6694 
6695   if (Args.hasFlag(options::OPT_fxl_pragma_pack,
6696                    options::OPT_fno_xl_pragma_pack, RawTriple.isOSAIX()))
6697     CmdArgs.push_back("-fxl-pragma-pack");
6698 
6699   // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
6700   if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
6701     renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
6702 
6703   bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
6704                                      options::OPT_fno_rewrite_imports, false);
6705   if (RewriteImports)
6706     CmdArgs.push_back("-frewrite-imports");
6707 
6708   // Enable rewrite includes if the user's asked for it or if we're generating
6709   // diagnostics.
6710   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
6711   // nice to enable this when doing a crashdump for modules as well.
6712   if (Args.hasFlag(options::OPT_frewrite_includes,
6713                    options::OPT_fno_rewrite_includes, false) ||
6714       (C.isForDiagnostics() && !HaveModules))
6715     CmdArgs.push_back("-frewrite-includes");
6716 
6717   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
6718   if (Arg *A = Args.getLastArg(options::OPT_traditional,
6719                                options::OPT_traditional_cpp)) {
6720     if (isa<PreprocessJobAction>(JA))
6721       CmdArgs.push_back("-traditional-cpp");
6722     else
6723       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
6724   }
6725 
6726   Args.AddLastArg(CmdArgs, options::OPT_dM);
6727   Args.AddLastArg(CmdArgs, options::OPT_dD);
6728   Args.AddLastArg(CmdArgs, options::OPT_dI);
6729 
6730   Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
6731 
6732   // Handle serialized diagnostics.
6733   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
6734     CmdArgs.push_back("-serialize-diagnostic-file");
6735     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
6736   }
6737 
6738   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
6739     CmdArgs.push_back("-fretain-comments-from-system-headers");
6740 
6741   // Forward -fcomment-block-commands to -cc1.
6742   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
6743   // Forward -fparse-all-comments to -cc1.
6744   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
6745 
6746   // Turn -fplugin=name.so into -load name.so
6747   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
6748     CmdArgs.push_back("-load");
6749     CmdArgs.push_back(A->getValue());
6750     A->claim();
6751   }
6752 
6753   // Turn -fplugin-arg-pluginname-key=value into
6754   // -plugin-arg-pluginname key=value
6755   // GCC has an actual plugin_argument struct with key/value pairs that it
6756   // passes to its plugins, but we don't, so just pass it on as-is.
6757   //
6758   // The syntax for -fplugin-arg- is ambiguous if both plugin name and
6759   // argument key are allowed to contain dashes. GCC therefore only
6760   // allows dashes in the key. We do the same.
6761   for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
6762     auto ArgValue = StringRef(A->getValue());
6763     auto FirstDashIndex = ArgValue.find('-');
6764     StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
6765     StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
6766 
6767     A->claim();
6768     if (FirstDashIndex == StringRef::npos || Arg.empty()) {
6769       if (PluginName.empty()) {
6770         D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
6771       } else {
6772         D.Diag(diag::warn_drv_missing_plugin_arg)
6773             << PluginName << A->getAsString(Args);
6774       }
6775       continue;
6776     }
6777 
6778     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
6779     CmdArgs.push_back(Args.MakeArgString(Arg));
6780   }
6781 
6782   // Forward -fpass-plugin=name.so to -cc1.
6783   for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
6784     CmdArgs.push_back(
6785         Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
6786     A->claim();
6787   }
6788 
6789   // Setup statistics file output.
6790   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
6791   if (!StatsFile.empty())
6792     CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
6793 
6794   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
6795   // parser.
6796   // -finclude-default-header flag is for preprocessor,
6797   // do not pass it to other cc1 commands when save-temps is enabled
6798   if (C.getDriver().isSaveTempsEnabled() &&
6799       !isa<PreprocessJobAction>(JA)) {
6800     for (auto Arg : Args.filtered(options::OPT_Xclang)) {
6801       Arg->claim();
6802       if (StringRef(Arg->getValue()) != "-finclude-default-header")
6803         CmdArgs.push_back(Arg->getValue());
6804     }
6805   }
6806   else {
6807     Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
6808   }
6809   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
6810     A->claim();
6811 
6812     // We translate this by hand to the -cc1 argument, since nightly test uses
6813     // it and developers have been trained to spell it with -mllvm. Both
6814     // spellings are now deprecated and should be removed.
6815     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
6816       CmdArgs.push_back("-disable-llvm-optzns");
6817     } else {
6818       A->render(Args, CmdArgs);
6819     }
6820   }
6821 
6822   // With -save-temps, we want to save the unoptimized bitcode output from the
6823   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
6824   // by the frontend.
6825   // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
6826   // has slightly different breakdown between stages.
6827   // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
6828   // pristine IR generated by the frontend. Ideally, a new compile action should
6829   // be added so both IR can be captured.
6830   if ((C.getDriver().isSaveTempsEnabled() ||
6831        JA.isHostOffloading(Action::OFK_OpenMP)) &&
6832       !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
6833       isa<CompileJobAction>(JA))
6834     CmdArgs.push_back("-disable-llvm-passes");
6835 
6836   Args.AddAllArgs(CmdArgs, options::OPT_undef);
6837 
6838   const char *Exec = D.getClangProgramPath();
6839 
6840   // Optionally embed the -cc1 level arguments into the debug info or a
6841   // section, for build analysis.
6842   // Also record command line arguments into the debug info if
6843   // -grecord-gcc-switches options is set on.
6844   // By default, -gno-record-gcc-switches is set on and no recording.
6845   auto GRecordSwitches =
6846       Args.hasFlag(options::OPT_grecord_command_line,
6847                    options::OPT_gno_record_command_line, false);
6848   auto FRecordSwitches =
6849       Args.hasFlag(options::OPT_frecord_command_line,
6850                    options::OPT_fno_record_command_line, false);
6851   if (FRecordSwitches && !Triple.isOSBinFormatELF())
6852     D.Diag(diag::err_drv_unsupported_opt_for_target)
6853         << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
6854         << TripleStr;
6855   if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
6856     ArgStringList OriginalArgs;
6857     for (const auto &Arg : Args)
6858       Arg->render(Args, OriginalArgs);
6859 
6860     SmallString<256> Flags;
6861     EscapeSpacesAndBackslashes(Exec, Flags);
6862     for (const char *OriginalArg : OriginalArgs) {
6863       SmallString<128> EscapedArg;
6864       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6865       Flags += " ";
6866       Flags += EscapedArg;
6867     }
6868     auto FlagsArgString = Args.MakeArgString(Flags);
6869     if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
6870       CmdArgs.push_back("-dwarf-debug-flags");
6871       CmdArgs.push_back(FlagsArgString);
6872     }
6873     if (FRecordSwitches) {
6874       CmdArgs.push_back("-record-command-line");
6875       CmdArgs.push_back(FlagsArgString);
6876     }
6877   }
6878 
6879   // Host-side cuda compilation receives all device-side outputs in a single
6880   // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
6881   if ((IsCuda || IsHIP) && CudaDeviceInput) {
6882       CmdArgs.push_back("-fcuda-include-gpubinary");
6883       CmdArgs.push_back(CudaDeviceInput->getFilename());
6884       if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
6885         CmdArgs.push_back("-fgpu-rdc");
6886   }
6887 
6888   if (IsCuda) {
6889     if (Args.hasFlag(options::OPT_fcuda_short_ptr,
6890                      options::OPT_fno_cuda_short_ptr, false))
6891       CmdArgs.push_back("-fcuda-short-ptr");
6892   }
6893 
6894   if (IsCuda || IsHIP) {
6895     // Determine the original source input.
6896     const Action *SourceAction = &JA;
6897     while (SourceAction->getKind() != Action::InputClass) {
6898       assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6899       SourceAction = SourceAction->getInputs()[0];
6900     }
6901     auto CUID = cast<InputAction>(SourceAction)->getId();
6902     if (!CUID.empty())
6903       CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
6904   }
6905 
6906   if (IsHIP) {
6907     CmdArgs.push_back("-fcuda-allow-variadic-functions");
6908     Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
6909   }
6910 
6911   if (IsCudaDevice || IsHIPDevice) {
6912     StringRef InlineThresh =
6913         Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
6914     if (!InlineThresh.empty()) {
6915       std::string ArgStr =
6916           std::string("-inline-threshold=") + InlineThresh.str();
6917       CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
6918     }
6919   }
6920 
6921   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
6922   // to specify the result of the compile phase on the host, so the meaningful
6923   // device declarations can be identified. Also, -fopenmp-is-device is passed
6924   // along to tell the frontend that it is generating code for a device, so that
6925   // only the relevant declarations are emitted.
6926   if (IsOpenMPDevice) {
6927     CmdArgs.push_back("-fopenmp-is-device");
6928     if (OpenMPDeviceInput) {
6929       CmdArgs.push_back("-fopenmp-host-ir-file-path");
6930       CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
6931     }
6932   }
6933 
6934   // Host-side OpenMP offloading recieves the device object files and embeds it
6935   // in a named section including the associated target triple and architecture.
6936   if (IsOpenMPHost && !OpenMPHostInputs.empty()) {
6937     auto InputFile = OpenMPHostInputs.begin();
6938     auto OpenMPTCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
6939     for (auto TI = OpenMPTCs.first, TE = OpenMPTCs.second; TI != TE;
6940          ++TI, ++InputFile) {
6941       const ToolChain *TC = TI->second;
6942       const ArgList &TCArgs = C.getArgsForToolChain(TC, "", Action::OFK_OpenMP);
6943       StringRef File =
6944           C.getArgs().MakeArgString(TC->getInputFilename(*InputFile));
6945 
6946       CmdArgs.push_back(
6947           Args.MakeArgString("-fembed-offload-object=" + File + "," +
6948                              Action::GetOffloadKindName(Action::OFK_OpenMP) +
6949                              "," + TC->getTripleString() + "," +
6950                              TCArgs.getLastArgValue(options::OPT_march_EQ)));
6951     }
6952   }
6953 
6954   if (Triple.isAMDGPU()) {
6955     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
6956 
6957     Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
6958                       options::OPT_mno_unsafe_fp_atomics);
6959   }
6960 
6961   // For all the host OpenMP offloading compile jobs we need to pass the targets
6962   // information using -fopenmp-targets= option.
6963   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
6964     SmallString<128> TargetInfo("-fopenmp-targets=");
6965 
6966     Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
6967     assert(Tgts && Tgts->getNumValues() &&
6968            "OpenMP offloading has to have targets specified.");
6969     for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
6970       if (i)
6971         TargetInfo += ',';
6972       // We need to get the string from the triple because it may be not exactly
6973       // the same as the one we get directly from the arguments.
6974       llvm::Triple T(Tgts->getValue(i));
6975       TargetInfo += T.getTriple();
6976     }
6977     CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
6978   }
6979 
6980   bool VirtualFunctionElimination =
6981       Args.hasFlag(options::OPT_fvirtual_function_elimination,
6982                    options::OPT_fno_virtual_function_elimination, false);
6983   if (VirtualFunctionElimination) {
6984     // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
6985     // in the future).
6986     if (LTOMode != LTOK_Full)
6987       D.Diag(diag::err_drv_argument_only_allowed_with)
6988           << "-fvirtual-function-elimination"
6989           << "-flto=full";
6990 
6991     CmdArgs.push_back("-fvirtual-function-elimination");
6992   }
6993 
6994   // VFE requires whole-program-vtables, and enables it by default.
6995   bool WholeProgramVTables = Args.hasFlag(
6996       options::OPT_fwhole_program_vtables,
6997       options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
6998   if (VirtualFunctionElimination && !WholeProgramVTables) {
6999     D.Diag(diag::err_drv_argument_not_allowed_with)
7000         << "-fno-whole-program-vtables"
7001         << "-fvirtual-function-elimination";
7002   }
7003 
7004   if (WholeProgramVTables) {
7005     // Propagate -fwhole-program-vtables if this is an LTO compile.
7006     if (IsUsingLTO)
7007       CmdArgs.push_back("-fwhole-program-vtables");
7008     // Check if we passed LTO options but they were suppressed because this is a
7009     // device offloading action, or we passed device offload LTO options which
7010     // were suppressed because this is not the device offload action.
7011     // Otherwise, issue an error.
7012     else if (!D.isUsingLTO(!IsDeviceOffloadAction))
7013       D.Diag(diag::err_drv_argument_only_allowed_with)
7014           << "-fwhole-program-vtables"
7015           << "-flto";
7016   }
7017 
7018   bool DefaultsSplitLTOUnit =
7019       (WholeProgramVTables || SanitizeArgs.needsLTO()) &&
7020       (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit());
7021   bool SplitLTOUnit =
7022       Args.hasFlag(options::OPT_fsplit_lto_unit,
7023                    options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
7024   if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7025     D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7026                                                     << "-fsanitize=cfi";
7027   if (SplitLTOUnit)
7028     CmdArgs.push_back("-fsplit-lto-unit");
7029 
7030   if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
7031                                options::OPT_fno_global_isel)) {
7032     CmdArgs.push_back("-mllvm");
7033     if (A->getOption().matches(options::OPT_fglobal_isel)) {
7034       CmdArgs.push_back("-global-isel=1");
7035 
7036       // GISel is on by default on AArch64 -O0, so don't bother adding
7037       // the fallback remarks for it. Other combinations will add a warning of
7038       // some kind.
7039       bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
7040       bool IsOptLevelSupported = false;
7041 
7042       Arg *A = Args.getLastArg(options::OPT_O_Group);
7043       if (Triple.getArch() == llvm::Triple::aarch64) {
7044         if (!A || A->getOption().matches(options::OPT_O0))
7045           IsOptLevelSupported = true;
7046       }
7047       if (!IsArchSupported || !IsOptLevelSupported) {
7048         CmdArgs.push_back("-mllvm");
7049         CmdArgs.push_back("-global-isel-abort=2");
7050 
7051         if (!IsArchSupported)
7052           D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
7053         else
7054           D.Diag(diag::warn_drv_global_isel_incomplete_opt);
7055       }
7056     } else {
7057       CmdArgs.push_back("-global-isel=0");
7058     }
7059   }
7060 
7061   if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
7062      CmdArgs.push_back("-forder-file-instrumentation");
7063      // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
7064      // on, we need to pass these flags as linker flags and that will be handled
7065      // outside of the compiler.
7066      if (!IsUsingLTO) {
7067        CmdArgs.push_back("-mllvm");
7068        CmdArgs.push_back("-enable-order-file-instrumentation");
7069      }
7070   }
7071 
7072   if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
7073                                options::OPT_fno_force_enable_int128)) {
7074     if (A->getOption().matches(options::OPT_fforce_enable_int128))
7075       CmdArgs.push_back("-fforce-enable-int128");
7076   }
7077 
7078   Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
7079                     options::OPT_fno_keep_static_consts);
7080   Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
7081                     options::OPT_fno_complete_member_pointers);
7082 
7083   if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
7084                     options::OPT_fno_cxx_static_destructors, true))
7085     CmdArgs.push_back("-fno-c++-static-destructors");
7086 
7087   addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
7088 
7089   if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
7090                                options::OPT_mno_outline_atomics)) {
7091     // Option -moutline-atomics supported for AArch64 target only.
7092     if (!Triple.isAArch64()) {
7093       D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
7094           << Triple.getArchName() << A->getOption().getName();
7095     } else {
7096       if (A->getOption().matches(options::OPT_moutline_atomics)) {
7097         CmdArgs.push_back("-target-feature");
7098         CmdArgs.push_back("+outline-atomics");
7099       } else {
7100         CmdArgs.push_back("-target-feature");
7101         CmdArgs.push_back("-outline-atomics");
7102       }
7103     }
7104   } else if (Triple.isAArch64() &&
7105              getToolChain().IsAArch64OutlineAtomicsDefault(Args)) {
7106     CmdArgs.push_back("-target-feature");
7107     CmdArgs.push_back("+outline-atomics");
7108   }
7109 
7110   if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
7111                    (TC.getTriple().isOSBinFormatELF() ||
7112                     TC.getTriple().isOSBinFormatCOFF()) &&
7113                        !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
7114                        !TC.getTriple().isOSNetBSD() &&
7115                        !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
7116                        !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
7117     CmdArgs.push_back("-faddrsig");
7118 
7119   if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
7120       (EH || AsyncUnwindTables || UnwindTables ||
7121        DebugInfoKind != codegenoptions::NoDebugInfo))
7122     CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
7123 
7124   if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
7125     std::string Str = A->getAsString(Args);
7126     if (!TC.getTriple().isOSBinFormatELF())
7127       D.Diag(diag::err_drv_unsupported_opt_for_target)
7128           << Str << TC.getTripleString();
7129     CmdArgs.push_back(Args.MakeArgString(Str));
7130   }
7131 
7132   // Add the output path to the object file for CodeView debug infos.
7133   if (EmitCodeView && Output.isFilename())
7134     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
7135                        Output.getFilename());
7136 
7137   // Add the "-o out -x type src.c" flags last. This is done primarily to make
7138   // the -cc1 command easier to edit when reproducing compiler crashes.
7139   if (Output.getType() == types::TY_Dependencies) {
7140     // Handled with other dependency code.
7141   } else if (Output.isFilename()) {
7142     if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
7143         Output.getType() == clang::driver::types::TY_IFS) {
7144       SmallString<128> OutputFilename(Output.getFilename());
7145       llvm::sys::path::replace_extension(OutputFilename, "ifs");
7146       CmdArgs.push_back("-o");
7147       CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7148     } else {
7149       CmdArgs.push_back("-o");
7150       CmdArgs.push_back(Output.getFilename());
7151     }
7152   } else {
7153     assert(Output.isNothing() && "Invalid output.");
7154   }
7155 
7156   addDashXForInput(Args, Input, CmdArgs);
7157 
7158   ArrayRef<InputInfo> FrontendInputs = Input;
7159   if (IsHeaderModulePrecompile)
7160     FrontendInputs = ModuleHeaderInputs;
7161   else if (IsExtractAPI)
7162     FrontendInputs = ExtractAPIInputs;
7163   else if (Input.isNothing())
7164     FrontendInputs = {};
7165 
7166   for (const InputInfo &Input : FrontendInputs) {
7167     if (Input.isFilename())
7168       CmdArgs.push_back(Input.getFilename());
7169     else
7170       Input.getInputArg().renderAsInput(Args, CmdArgs);
7171   }
7172 
7173   if (D.CC1Main && !D.CCGenDiagnostics) {
7174     // Invoke the CC1 directly in this process
7175     C.addCommand(std::make_unique<CC1Command>(JA, *this,
7176                                               ResponseFileSupport::AtFileUTF8(),
7177                                               Exec, CmdArgs, Inputs, Output));
7178   } else {
7179     C.addCommand(std::make_unique<Command>(JA, *this,
7180                                            ResponseFileSupport::AtFileUTF8(),
7181                                            Exec, CmdArgs, Inputs, Output));
7182   }
7183 
7184   // Make the compile command echo its inputs for /showFilenames.
7185   if (Output.getType() == types::TY_Object &&
7186       Args.hasFlag(options::OPT__SLASH_showFilenames,
7187                    options::OPT__SLASH_showFilenames_, false)) {
7188     C.getJobs().getJobs().back()->PrintInputFilenames = true;
7189   }
7190 
7191   if (Arg *A = Args.getLastArg(options::OPT_pg))
7192     if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
7193         !Args.hasArg(options::OPT_mfentry))
7194       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
7195                                                       << A->getAsString(Args);
7196 
7197   // Claim some arguments which clang supports automatically.
7198 
7199   // -fpch-preprocess is used with gcc to add a special marker in the output to
7200   // include the PCH file.
7201   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
7202 
7203   // Claim some arguments which clang doesn't support, but we don't
7204   // care to warn the user about.
7205   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
7206   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
7207 
7208   // Disable warnings for clang -E -emit-llvm foo.c
7209   Args.ClaimAllArgs(options::OPT_emit_llvm);
7210 }
7211 
7212 Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
7213     // CAUTION! The first constructor argument ("clang") is not arbitrary,
7214     // as it is for other tools. Some operations on a Tool actually test
7215     // whether that tool is Clang based on the Tool's Name as a string.
7216     : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
7217 
7218 Clang::~Clang() {}
7219 
7220 /// Add options related to the Objective-C runtime/ABI.
7221 ///
7222 /// Returns true if the runtime is non-fragile.
7223 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
7224                                       const InputInfoList &inputs,
7225                                       ArgStringList &cmdArgs,
7226                                       RewriteKind rewriteKind) const {
7227   // Look for the controlling runtime option.
7228   Arg *runtimeArg =
7229       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
7230                       options::OPT_fobjc_runtime_EQ);
7231 
7232   // Just forward -fobjc-runtime= to the frontend.  This supercedes
7233   // options about fragility.
7234   if (runtimeArg &&
7235       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
7236     ObjCRuntime runtime;
7237     StringRef value = runtimeArg->getValue();
7238     if (runtime.tryParse(value)) {
7239       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
7240           << value;
7241     }
7242     if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
7243         (runtime.getVersion() >= VersionTuple(2, 0)))
7244       if (!getToolChain().getTriple().isOSBinFormatELF() &&
7245           !getToolChain().getTriple().isOSBinFormatCOFF()) {
7246         getToolChain().getDriver().Diag(
7247             diag::err_drv_gnustep_objc_runtime_incompatible_binary)
7248           << runtime.getVersion().getMajor();
7249       }
7250 
7251     runtimeArg->render(args, cmdArgs);
7252     return runtime;
7253   }
7254 
7255   // Otherwise, we'll need the ABI "version".  Version numbers are
7256   // slightly confusing for historical reasons:
7257   //   1 - Traditional "fragile" ABI
7258   //   2 - Non-fragile ABI, version 1
7259   //   3 - Non-fragile ABI, version 2
7260   unsigned objcABIVersion = 1;
7261   // If -fobjc-abi-version= is present, use that to set the version.
7262   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
7263     StringRef value = abiArg->getValue();
7264     if (value == "1")
7265       objcABIVersion = 1;
7266     else if (value == "2")
7267       objcABIVersion = 2;
7268     else if (value == "3")
7269       objcABIVersion = 3;
7270     else
7271       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
7272   } else {
7273     // Otherwise, determine if we are using the non-fragile ABI.
7274     bool nonFragileABIIsDefault =
7275         (rewriteKind == RK_NonFragile ||
7276          (rewriteKind == RK_None &&
7277           getToolChain().IsObjCNonFragileABIDefault()));
7278     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
7279                      options::OPT_fno_objc_nonfragile_abi,
7280                      nonFragileABIIsDefault)) {
7281 // Determine the non-fragile ABI version to use.
7282 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
7283       unsigned nonFragileABIVersion = 1;
7284 #else
7285       unsigned nonFragileABIVersion = 2;
7286 #endif
7287 
7288       if (Arg *abiArg =
7289               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
7290         StringRef value = abiArg->getValue();
7291         if (value == "1")
7292           nonFragileABIVersion = 1;
7293         else if (value == "2")
7294           nonFragileABIVersion = 2;
7295         else
7296           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
7297               << value;
7298       }
7299 
7300       objcABIVersion = 1 + nonFragileABIVersion;
7301     } else {
7302       objcABIVersion = 1;
7303     }
7304   }
7305 
7306   // We don't actually care about the ABI version other than whether
7307   // it's non-fragile.
7308   bool isNonFragile = objcABIVersion != 1;
7309 
7310   // If we have no runtime argument, ask the toolchain for its default runtime.
7311   // However, the rewriter only really supports the Mac runtime, so assume that.
7312   ObjCRuntime runtime;
7313   if (!runtimeArg) {
7314     switch (rewriteKind) {
7315     case RK_None:
7316       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7317       break;
7318     case RK_Fragile:
7319       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
7320       break;
7321     case RK_NonFragile:
7322       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7323       break;
7324     }
7325 
7326     // -fnext-runtime
7327   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
7328     // On Darwin, make this use the default behavior for the toolchain.
7329     if (getToolChain().getTriple().isOSDarwin()) {
7330       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7331 
7332       // Otherwise, build for a generic macosx port.
7333     } else {
7334       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7335     }
7336 
7337     // -fgnu-runtime
7338   } else {
7339     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
7340     // Legacy behaviour is to target the gnustep runtime if we are in
7341     // non-fragile mode or the GCC runtime in fragile mode.
7342     if (isNonFragile)
7343       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
7344     else
7345       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
7346   }
7347 
7348   if (llvm::any_of(inputs, [](const InputInfo &input) {
7349         return types::isObjC(input.getType());
7350       }))
7351     cmdArgs.push_back(
7352         args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
7353   return runtime;
7354 }
7355 
7356 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
7357   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
7358   I += HaveDash;
7359   return !HaveDash;
7360 }
7361 
7362 namespace {
7363 struct EHFlags {
7364   bool Synch = false;
7365   bool Asynch = false;
7366   bool NoUnwindC = false;
7367 };
7368 } // end anonymous namespace
7369 
7370 /// /EH controls whether to run destructor cleanups when exceptions are
7371 /// thrown.  There are three modifiers:
7372 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
7373 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
7374 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
7375 /// - c: Assume that extern "C" functions are implicitly nounwind.
7376 /// The default is /EHs-c-, meaning cleanups are disabled.
7377 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
7378   EHFlags EH;
7379 
7380   std::vector<std::string> EHArgs =
7381       Args.getAllArgValues(options::OPT__SLASH_EH);
7382   for (auto EHVal : EHArgs) {
7383     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
7384       switch (EHVal[I]) {
7385       case 'a':
7386         EH.Asynch = maybeConsumeDash(EHVal, I);
7387         if (EH.Asynch)
7388           EH.Synch = false;
7389         continue;
7390       case 'c':
7391         EH.NoUnwindC = maybeConsumeDash(EHVal, I);
7392         continue;
7393       case 's':
7394         EH.Synch = maybeConsumeDash(EHVal, I);
7395         if (EH.Synch)
7396           EH.Asynch = false;
7397         continue;
7398       default:
7399         break;
7400       }
7401       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
7402       break;
7403     }
7404   }
7405   // The /GX, /GX- flags are only processed if there are not /EH flags.
7406   // The default is that /GX is not specified.
7407   if (EHArgs.empty() &&
7408       Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
7409                    /*Default=*/false)) {
7410     EH.Synch = true;
7411     EH.NoUnwindC = true;
7412   }
7413 
7414   return EH;
7415 }
7416 
7417 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
7418                            ArgStringList &CmdArgs,
7419                            codegenoptions::DebugInfoKind *DebugInfoKind,
7420                            bool *EmitCodeView) const {
7421   unsigned RTOptionID = options::OPT__SLASH_MT;
7422   bool isNVPTX = getToolChain().getTriple().isNVPTX();
7423 
7424   if (Args.hasArg(options::OPT__SLASH_LDd))
7425     // The /LDd option implies /MTd. The dependent lib part can be overridden,
7426     // but defining _DEBUG is sticky.
7427     RTOptionID = options::OPT__SLASH_MTd;
7428 
7429   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
7430     RTOptionID = A->getOption().getID();
7431 
7432   StringRef FlagForCRT;
7433   switch (RTOptionID) {
7434   case options::OPT__SLASH_MD:
7435     if (Args.hasArg(options::OPT__SLASH_LDd))
7436       CmdArgs.push_back("-D_DEBUG");
7437     CmdArgs.push_back("-D_MT");
7438     CmdArgs.push_back("-D_DLL");
7439     FlagForCRT = "--dependent-lib=msvcrt";
7440     break;
7441   case options::OPT__SLASH_MDd:
7442     CmdArgs.push_back("-D_DEBUG");
7443     CmdArgs.push_back("-D_MT");
7444     CmdArgs.push_back("-D_DLL");
7445     FlagForCRT = "--dependent-lib=msvcrtd";
7446     break;
7447   case options::OPT__SLASH_MT:
7448     if (Args.hasArg(options::OPT__SLASH_LDd))
7449       CmdArgs.push_back("-D_DEBUG");
7450     CmdArgs.push_back("-D_MT");
7451     CmdArgs.push_back("-flto-visibility-public-std");
7452     FlagForCRT = "--dependent-lib=libcmt";
7453     break;
7454   case options::OPT__SLASH_MTd:
7455     CmdArgs.push_back("-D_DEBUG");
7456     CmdArgs.push_back("-D_MT");
7457     CmdArgs.push_back("-flto-visibility-public-std");
7458     FlagForCRT = "--dependent-lib=libcmtd";
7459     break;
7460   default:
7461     llvm_unreachable("Unexpected option ID.");
7462   }
7463 
7464   if (Args.hasArg(options::OPT__SLASH_Zl)) {
7465     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
7466   } else {
7467     CmdArgs.push_back(FlagForCRT.data());
7468 
7469     // This provides POSIX compatibility (maps 'open' to '_open'), which most
7470     // users want.  The /Za flag to cl.exe turns this off, but it's not
7471     // implemented in clang.
7472     CmdArgs.push_back("--dependent-lib=oldnames");
7473   }
7474 
7475   if (Arg *ShowIncludes =
7476           Args.getLastArg(options::OPT__SLASH_showIncludes,
7477                           options::OPT__SLASH_showIncludes_user)) {
7478     CmdArgs.push_back("--show-includes");
7479     if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
7480       CmdArgs.push_back("-sys-header-deps");
7481   }
7482 
7483   // This controls whether or not we emit RTTI data for polymorphic types.
7484   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
7485                    /*Default=*/false))
7486     CmdArgs.push_back("-fno-rtti-data");
7487 
7488   // This controls whether or not we emit stack-protector instrumentation.
7489   // In MSVC, Buffer Security Check (/GS) is on by default.
7490   if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
7491                                /*Default=*/true)) {
7492     CmdArgs.push_back("-stack-protector");
7493     CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
7494   }
7495 
7496   // Emit CodeView if -Z7 or -gline-tables-only are present.
7497   if (Arg *DebugInfoArg = Args.getLastArg(options::OPT__SLASH_Z7,
7498                                           options::OPT_gline_tables_only)) {
7499     *EmitCodeView = true;
7500     if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
7501       *DebugInfoKind = codegenoptions::DebugInfoConstructor;
7502     else
7503       *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
7504   } else {
7505     *EmitCodeView = false;
7506   }
7507 
7508   const Driver &D = getToolChain().getDriver();
7509 
7510   // This controls whether or not we perform JustMyCode instrumentation.
7511   if (Args.hasFlag(options::OPT__SLASH_JMC, options::OPT__SLASH_JMC_,
7512                    /*Default=*/false)) {
7513     if (*EmitCodeView && *DebugInfoKind >= codegenoptions::DebugInfoConstructor)
7514       CmdArgs.push_back("-fjmc");
7515     else
7516       D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
7517                                                            << "'/Zi', '/Z7'";
7518   }
7519 
7520   EHFlags EH = parseClangCLEHFlags(D, Args);
7521   if (!isNVPTX && (EH.Synch || EH.Asynch)) {
7522     if (types::isCXX(InputType))
7523       CmdArgs.push_back("-fcxx-exceptions");
7524     CmdArgs.push_back("-fexceptions");
7525   }
7526   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
7527     CmdArgs.push_back("-fexternc-nounwind");
7528 
7529   // /EP should expand to -E -P.
7530   if (Args.hasArg(options::OPT__SLASH_EP)) {
7531     CmdArgs.push_back("-E");
7532     CmdArgs.push_back("-P");
7533   }
7534 
7535   unsigned VolatileOptionID;
7536   if (getToolChain().getTriple().isX86())
7537     VolatileOptionID = options::OPT__SLASH_volatile_ms;
7538   else
7539     VolatileOptionID = options::OPT__SLASH_volatile_iso;
7540 
7541   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
7542     VolatileOptionID = A->getOption().getID();
7543 
7544   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
7545     CmdArgs.push_back("-fms-volatile");
7546 
7547  if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
7548                   options::OPT__SLASH_Zc_dllexportInlines,
7549                   false)) {
7550   CmdArgs.push_back("-fno-dllexport-inlines");
7551  }
7552 
7553   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
7554   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
7555   if (MostGeneralArg && BestCaseArg)
7556     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
7557         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
7558 
7559   if (MostGeneralArg) {
7560     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
7561     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
7562     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
7563 
7564     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
7565     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
7566     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
7567       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
7568           << FirstConflict->getAsString(Args)
7569           << SecondConflict->getAsString(Args);
7570 
7571     if (SingleArg)
7572       CmdArgs.push_back("-fms-memptr-rep=single");
7573     else if (MultipleArg)
7574       CmdArgs.push_back("-fms-memptr-rep=multiple");
7575     else
7576       CmdArgs.push_back("-fms-memptr-rep=virtual");
7577   }
7578 
7579   // Parse the default calling convention options.
7580   if (Arg *CCArg =
7581           Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
7582                           options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
7583                           options::OPT__SLASH_Gregcall)) {
7584     unsigned DCCOptId = CCArg->getOption().getID();
7585     const char *DCCFlag = nullptr;
7586     bool ArchSupported = !isNVPTX;
7587     llvm::Triple::ArchType Arch = getToolChain().getArch();
7588     switch (DCCOptId) {
7589     case options::OPT__SLASH_Gd:
7590       DCCFlag = "-fdefault-calling-conv=cdecl";
7591       break;
7592     case options::OPT__SLASH_Gr:
7593       ArchSupported = Arch == llvm::Triple::x86;
7594       DCCFlag = "-fdefault-calling-conv=fastcall";
7595       break;
7596     case options::OPT__SLASH_Gz:
7597       ArchSupported = Arch == llvm::Triple::x86;
7598       DCCFlag = "-fdefault-calling-conv=stdcall";
7599       break;
7600     case options::OPT__SLASH_Gv:
7601       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
7602       DCCFlag = "-fdefault-calling-conv=vectorcall";
7603       break;
7604     case options::OPT__SLASH_Gregcall:
7605       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
7606       DCCFlag = "-fdefault-calling-conv=regcall";
7607       break;
7608     }
7609 
7610     // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
7611     if (ArchSupported && DCCFlag)
7612       CmdArgs.push_back(DCCFlag);
7613   }
7614 
7615   Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
7616 
7617   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
7618     CmdArgs.push_back("-fdiagnostics-format");
7619     CmdArgs.push_back("msvc");
7620   }
7621 
7622   if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
7623     StringRef GuardArgs = A->getValue();
7624     // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
7625     // "ehcont-".
7626     if (GuardArgs.equals_insensitive("cf")) {
7627       // Emit CFG instrumentation and the table of address-taken functions.
7628       CmdArgs.push_back("-cfguard");
7629     } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
7630       // Emit only the table of address-taken functions.
7631       CmdArgs.push_back("-cfguard-no-checks");
7632     } else if (GuardArgs.equals_insensitive("ehcont")) {
7633       // Emit EH continuation table.
7634       CmdArgs.push_back("-ehcontguard");
7635     } else if (GuardArgs.equals_insensitive("cf-") ||
7636                GuardArgs.equals_insensitive("ehcont-")) {
7637       // Do nothing, but we might want to emit a security warning in future.
7638     } else {
7639       D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
7640     }
7641   }
7642 }
7643 
7644 const char *Clang::getBaseInputName(const ArgList &Args,
7645                                     const InputInfo &Input) {
7646   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
7647 }
7648 
7649 const char *Clang::getBaseInputStem(const ArgList &Args,
7650                                     const InputInfoList &Inputs) {
7651   const char *Str = getBaseInputName(Args, Inputs[0]);
7652 
7653   if (const char *End = strrchr(Str, '.'))
7654     return Args.MakeArgString(std::string(Str, End));
7655 
7656   return Str;
7657 }
7658 
7659 const char *Clang::getDependencyFileName(const ArgList &Args,
7660                                          const InputInfoList &Inputs) {
7661   // FIXME: Think about this more.
7662 
7663   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
7664     SmallString<128> OutputFilename(OutputOpt->getValue());
7665     llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
7666     return Args.MakeArgString(OutputFilename);
7667   }
7668 
7669   return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
7670 }
7671 
7672 // Begin ClangAs
7673 
7674 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
7675                                 ArgStringList &CmdArgs) const {
7676   StringRef CPUName;
7677   StringRef ABIName;
7678   const llvm::Triple &Triple = getToolChain().getTriple();
7679   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
7680 
7681   CmdArgs.push_back("-target-abi");
7682   CmdArgs.push_back(ABIName.data());
7683 }
7684 
7685 void ClangAs::AddX86TargetArgs(const ArgList &Args,
7686                                ArgStringList &CmdArgs) const {
7687   addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
7688                         /*IsLTO=*/false);
7689 
7690   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
7691     StringRef Value = A->getValue();
7692     if (Value == "intel" || Value == "att") {
7693       CmdArgs.push_back("-mllvm");
7694       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
7695     } else {
7696       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
7697           << A->getOption().getName() << Value;
7698     }
7699   }
7700 }
7701 
7702 void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
7703                                ArgStringList &CmdArgs) const {
7704   const llvm::Triple &Triple = getToolChain().getTriple();
7705   StringRef ABIName = riscv::getRISCVABI(Args, Triple);
7706 
7707   CmdArgs.push_back("-target-abi");
7708   CmdArgs.push_back(ABIName.data());
7709 }
7710 
7711 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
7712                            const InputInfo &Output, const InputInfoList &Inputs,
7713                            const ArgList &Args,
7714                            const char *LinkingOutput) const {
7715   ArgStringList CmdArgs;
7716 
7717   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
7718   const InputInfo &Input = Inputs[0];
7719 
7720   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
7721   const std::string &TripleStr = Triple.getTriple();
7722   const auto &D = getToolChain().getDriver();
7723 
7724   // Don't warn about "clang -w -c foo.s"
7725   Args.ClaimAllArgs(options::OPT_w);
7726   // and "clang -emit-llvm -c foo.s"
7727   Args.ClaimAllArgs(options::OPT_emit_llvm);
7728 
7729   claimNoWarnArgs(Args);
7730 
7731   // Invoke ourselves in -cc1as mode.
7732   //
7733   // FIXME: Implement custom jobs for internal actions.
7734   CmdArgs.push_back("-cc1as");
7735 
7736   // Add the "effective" target triple.
7737   CmdArgs.push_back("-triple");
7738   CmdArgs.push_back(Args.MakeArgString(TripleStr));
7739 
7740   // Set the output mode, we currently only expect to be used as a real
7741   // assembler.
7742   CmdArgs.push_back("-filetype");
7743   CmdArgs.push_back("obj");
7744 
7745   // Set the main file name, so that debug info works even with
7746   // -save-temps or preprocessed assembly.
7747   CmdArgs.push_back("-main-file-name");
7748   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
7749 
7750   // Add the target cpu
7751   std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
7752   if (!CPU.empty()) {
7753     CmdArgs.push_back("-target-cpu");
7754     CmdArgs.push_back(Args.MakeArgString(CPU));
7755   }
7756 
7757   // Add the target features
7758   getTargetFeatures(D, Triple, Args, CmdArgs, true);
7759 
7760   // Ignore explicit -force_cpusubtype_ALL option.
7761   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
7762 
7763   // Pass along any -I options so we get proper .include search paths.
7764   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
7765 
7766   // Determine the original source input.
7767   auto FindSource = [](const Action *S) -> const Action * {
7768     while (S->getKind() != Action::InputClass) {
7769       assert(!S->getInputs().empty() && "unexpected root action!");
7770       S = S->getInputs()[0];
7771     }
7772     return S;
7773   };
7774   const Action *SourceAction = FindSource(&JA);
7775 
7776   // Forward -g and handle debug info related flags, assuming we are dealing
7777   // with an actual assembly file.
7778   bool WantDebug = false;
7779   Args.ClaimAllArgs(options::OPT_g_Group);
7780   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
7781     WantDebug = !A->getOption().matches(options::OPT_g0) &&
7782                 !A->getOption().matches(options::OPT_ggdb0);
7783 
7784   unsigned DwarfVersion = ParseDebugDefaultVersion(getToolChain(), Args);
7785   if (const Arg *GDwarfN = getDwarfNArg(Args))
7786     DwarfVersion = DwarfVersionNum(GDwarfN->getSpelling());
7787 
7788   if (DwarfVersion == 0)
7789     DwarfVersion = getToolChain().GetDefaultDwarfVersion();
7790 
7791   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
7792 
7793   // Add the -fdebug-compilation-dir flag if needed.
7794   const char *DebugCompilationDir =
7795       addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
7796 
7797   if (SourceAction->getType() == types::TY_Asm ||
7798       SourceAction->getType() == types::TY_PP_Asm) {
7799     // You might think that it would be ok to set DebugInfoKind outside of
7800     // the guard for source type, however there is a test which asserts
7801     // that some assembler invocation receives no -debug-info-kind,
7802     // and it's not clear whether that test is just overly restrictive.
7803     DebugInfoKind = (WantDebug ? codegenoptions::DebugInfoConstructor
7804                                : codegenoptions::NoDebugInfo);
7805 
7806     addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
7807                          CmdArgs);
7808 
7809     // Set the AT_producer to the clang version when using the integrated
7810     // assembler on assembly source files.
7811     CmdArgs.push_back("-dwarf-debug-producer");
7812     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
7813 
7814     // And pass along -I options
7815     Args.AddAllArgs(CmdArgs, options::OPT_I);
7816   }
7817   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
7818                           llvm::DebuggerKind::Default);
7819   renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
7820   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
7821 
7822 
7823   // Handle -fPIC et al -- the relocation-model affects the assembler
7824   // for some targets.
7825   llvm::Reloc::Model RelocationModel;
7826   unsigned PICLevel;
7827   bool IsPIE;
7828   std::tie(RelocationModel, PICLevel, IsPIE) =
7829       ParsePICArgs(getToolChain(), Args);
7830 
7831   const char *RMName = RelocationModelName(RelocationModel);
7832   if (RMName) {
7833     CmdArgs.push_back("-mrelocation-model");
7834     CmdArgs.push_back(RMName);
7835   }
7836 
7837   // Optionally embed the -cc1as level arguments into the debug info, for build
7838   // analysis.
7839   if (getToolChain().UseDwarfDebugFlags()) {
7840     ArgStringList OriginalArgs;
7841     for (const auto &Arg : Args)
7842       Arg->render(Args, OriginalArgs);
7843 
7844     SmallString<256> Flags;
7845     const char *Exec = getToolChain().getDriver().getClangProgramPath();
7846     EscapeSpacesAndBackslashes(Exec, Flags);
7847     for (const char *OriginalArg : OriginalArgs) {
7848       SmallString<128> EscapedArg;
7849       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
7850       Flags += " ";
7851       Flags += EscapedArg;
7852     }
7853     CmdArgs.push_back("-dwarf-debug-flags");
7854     CmdArgs.push_back(Args.MakeArgString(Flags));
7855   }
7856 
7857   // FIXME: Add -static support, once we have it.
7858 
7859   // Add target specific flags.
7860   switch (getToolChain().getArch()) {
7861   default:
7862     break;
7863 
7864   case llvm::Triple::mips:
7865   case llvm::Triple::mipsel:
7866   case llvm::Triple::mips64:
7867   case llvm::Triple::mips64el:
7868     AddMIPSTargetArgs(Args, CmdArgs);
7869     break;
7870 
7871   case llvm::Triple::x86:
7872   case llvm::Triple::x86_64:
7873     AddX86TargetArgs(Args, CmdArgs);
7874     break;
7875 
7876   case llvm::Triple::arm:
7877   case llvm::Triple::armeb:
7878   case llvm::Triple::thumb:
7879   case llvm::Triple::thumbeb:
7880     // This isn't in AddARMTargetArgs because we want to do this for assembly
7881     // only, not C/C++.
7882     if (Args.hasFlag(options::OPT_mdefault_build_attributes,
7883                      options::OPT_mno_default_build_attributes, true)) {
7884         CmdArgs.push_back("-mllvm");
7885         CmdArgs.push_back("-arm-add-build-attributes");
7886     }
7887     break;
7888 
7889   case llvm::Triple::aarch64:
7890   case llvm::Triple::aarch64_32:
7891   case llvm::Triple::aarch64_be:
7892     if (Args.hasArg(options::OPT_mmark_bti_property)) {
7893       CmdArgs.push_back("-mllvm");
7894       CmdArgs.push_back("-aarch64-mark-bti-property");
7895     }
7896     break;
7897 
7898   case llvm::Triple::riscv32:
7899   case llvm::Triple::riscv64:
7900     AddRISCVTargetArgs(Args, CmdArgs);
7901     break;
7902   }
7903 
7904   // Consume all the warning flags. Usually this would be handled more
7905   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
7906   // doesn't handle that so rather than warning about unused flags that are
7907   // actually used, we'll lie by omission instead.
7908   // FIXME: Stop lying and consume only the appropriate driver flags
7909   Args.ClaimAllArgs(options::OPT_W_Group);
7910 
7911   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
7912                                     getToolChain().getDriver());
7913 
7914   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
7915 
7916   if (DebugInfoKind > codegenoptions::NoDebugInfo && Output.isFilename())
7917     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
7918                        Output.getFilename());
7919 
7920   // Fixup any previous commands that use -object-file-name because when we
7921   // generated them, the final .obj name wasn't yet known.
7922   for (Command &J : C.getJobs()) {
7923     if (SourceAction != FindSource(&J.getSource()))
7924       continue;
7925     auto &JArgs = J.getArguments();
7926     for (unsigned I = 0; I < JArgs.size(); ++I) {
7927       if (StringRef(JArgs[I]).startswith("-object-file-name=") &&
7928           Output.isFilename()) {
7929         ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
7930         addDebugObjectName(Args, NewArgs, DebugCompilationDir,
7931                            Output.getFilename());
7932         NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
7933         J.replaceArguments(NewArgs);
7934         break;
7935       }
7936     }
7937   }
7938 
7939   assert(Output.isFilename() && "Unexpected lipo output.");
7940   CmdArgs.push_back("-o");
7941   CmdArgs.push_back(Output.getFilename());
7942 
7943   const llvm::Triple &T = getToolChain().getTriple();
7944   Arg *A;
7945   if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
7946       T.isOSBinFormatELF()) {
7947     CmdArgs.push_back("-split-dwarf-output");
7948     CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
7949   }
7950 
7951   if (Triple.isAMDGPU())
7952     handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
7953 
7954   assert(Input.isFilename() && "Invalid input.");
7955   CmdArgs.push_back(Input.getFilename());
7956 
7957   const char *Exec = getToolChain().getDriver().getClangProgramPath();
7958   if (D.CC1Main && !D.CCGenDiagnostics) {
7959     // Invoke cc1as directly in this process.
7960     C.addCommand(std::make_unique<CC1Command>(JA, *this,
7961                                               ResponseFileSupport::AtFileUTF8(),
7962                                               Exec, CmdArgs, Inputs, Output));
7963   } else {
7964     C.addCommand(std::make_unique<Command>(JA, *this,
7965                                            ResponseFileSupport::AtFileUTF8(),
7966                                            Exec, CmdArgs, Inputs, Output));
7967   }
7968 }
7969 
7970 // Begin OffloadBundler
7971 
7972 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
7973                                   const InputInfo &Output,
7974                                   const InputInfoList &Inputs,
7975                                   const llvm::opt::ArgList &TCArgs,
7976                                   const char *LinkingOutput) const {
7977   // The version with only one output is expected to refer to a bundling job.
7978   assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
7979 
7980   // The bundling command looks like this:
7981   // clang-offload-bundler -type=bc
7982   //   -targets=host-triple,openmp-triple1,openmp-triple2
7983   //   -output=output_file
7984   //   -input=unbundle_file_host
7985   //   -input=unbundle_file_tgt1
7986   //   -input=unbundle_file_tgt2
7987 
7988   ArgStringList CmdArgs;
7989 
7990   // Get the type.
7991   CmdArgs.push_back(TCArgs.MakeArgString(
7992       Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
7993 
7994   assert(JA.getInputs().size() == Inputs.size() &&
7995          "Not have inputs for all dependence actions??");
7996 
7997   // Get the targets.
7998   SmallString<128> Triples;
7999   Triples += "-targets=";
8000   for (unsigned I = 0; I < Inputs.size(); ++I) {
8001     if (I)
8002       Triples += ',';
8003 
8004     // Find ToolChain for this input.
8005     Action::OffloadKind CurKind = Action::OFK_Host;
8006     const ToolChain *CurTC = &getToolChain();
8007     const Action *CurDep = JA.getInputs()[I];
8008 
8009     if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
8010       CurTC = nullptr;
8011       OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
8012         assert(CurTC == nullptr && "Expected one dependence!");
8013         CurKind = A->getOffloadingDeviceKind();
8014         CurTC = TC;
8015       });
8016     }
8017     Triples += Action::GetOffloadKindName(CurKind);
8018     Triples += '-';
8019     Triples += CurTC->getTriple().normalize();
8020     if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
8021         !StringRef(CurDep->getOffloadingArch()).empty()) {
8022       Triples += '-';
8023       Triples += CurDep->getOffloadingArch();
8024     }
8025 
8026     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8027     //       with each toolchain.
8028     StringRef GPUArchName;
8029     if (CurKind == Action::OFK_OpenMP) {
8030       // Extract GPUArch from -march argument in TC argument list.
8031       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8032         auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
8033         auto Arch = ArchStr.startswith_insensitive("-march=");
8034         if (Arch) {
8035           GPUArchName = ArchStr.substr(7);
8036           Triples += "-";
8037           break;
8038         }
8039       }
8040       Triples += GPUArchName.str();
8041     }
8042   }
8043   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8044 
8045   // Get bundled file command.
8046   CmdArgs.push_back(
8047       TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
8048 
8049   // Get unbundled files command.
8050   for (unsigned I = 0; I < Inputs.size(); ++I) {
8051     SmallString<128> UB;
8052     UB += "-input=";
8053 
8054     // Find ToolChain for this input.
8055     const ToolChain *CurTC = &getToolChain();
8056     if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
8057       CurTC = nullptr;
8058       OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
8059         assert(CurTC == nullptr && "Expected one dependence!");
8060         CurTC = TC;
8061       });
8062       UB += C.addTempFile(
8063           C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
8064     } else {
8065       UB += CurTC->getInputFilename(Inputs[I]);
8066     }
8067     CmdArgs.push_back(TCArgs.MakeArgString(UB));
8068   }
8069   // All the inputs are encoded as commands.
8070   C.addCommand(std::make_unique<Command>(
8071       JA, *this, ResponseFileSupport::None(),
8072       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8073       CmdArgs, None, Output));
8074 }
8075 
8076 void OffloadBundler::ConstructJobMultipleOutputs(
8077     Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
8078     const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
8079     const char *LinkingOutput) const {
8080   // The version with multiple outputs is expected to refer to a unbundling job.
8081   auto &UA = cast<OffloadUnbundlingJobAction>(JA);
8082 
8083   // The unbundling command looks like this:
8084   // clang-offload-bundler -type=bc
8085   //   -targets=host-triple,openmp-triple1,openmp-triple2
8086   //   -input=input_file
8087   //   -output=unbundle_file_host
8088   //   -output=unbundle_file_tgt1
8089   //   -output=unbundle_file_tgt2
8090   //   -unbundle
8091 
8092   ArgStringList CmdArgs;
8093 
8094   assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
8095   InputInfo Input = Inputs.front();
8096 
8097   // Get the type.
8098   CmdArgs.push_back(TCArgs.MakeArgString(
8099       Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
8100 
8101   // Get the targets.
8102   SmallString<128> Triples;
8103   Triples += "-targets=";
8104   auto DepInfo = UA.getDependentActionsInfo();
8105   for (unsigned I = 0; I < DepInfo.size(); ++I) {
8106     if (I)
8107       Triples += ',';
8108 
8109     auto &Dep = DepInfo[I];
8110     Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
8111     Triples += '-';
8112     Triples += Dep.DependentToolChain->getTriple().normalize();
8113     if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
8114          Dep.DependentOffloadKind == Action::OFK_Cuda) &&
8115         !Dep.DependentBoundArch.empty()) {
8116       Triples += '-';
8117       Triples += Dep.DependentBoundArch;
8118     }
8119     // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8120     //       with each toolchain.
8121     StringRef GPUArchName;
8122     if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
8123       // Extract GPUArch from -march argument in TC argument list.
8124       for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8125         StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
8126         auto Arch = ArchStr.startswith_insensitive("-march=");
8127         if (Arch) {
8128           GPUArchName = ArchStr.substr(7);
8129           Triples += "-";
8130           break;
8131         }
8132       }
8133       Triples += GPUArchName.str();
8134     }
8135   }
8136 
8137   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8138 
8139   // Get bundled file command.
8140   CmdArgs.push_back(
8141       TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
8142 
8143   // Get unbundled files command.
8144   for (unsigned I = 0; I < Outputs.size(); ++I) {
8145     SmallString<128> UB;
8146     UB += "-output=";
8147     UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
8148     CmdArgs.push_back(TCArgs.MakeArgString(UB));
8149   }
8150   CmdArgs.push_back("-unbundle");
8151   CmdArgs.push_back("-allow-missing-bundles");
8152 
8153   // All the inputs are encoded as commands.
8154   C.addCommand(std::make_unique<Command>(
8155       JA, *this, ResponseFileSupport::None(),
8156       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8157       CmdArgs, None, Outputs));
8158 }
8159 
8160 void OffloadWrapper::ConstructJob(Compilation &C, const JobAction &JA,
8161                                   const InputInfo &Output,
8162                                   const InputInfoList &Inputs,
8163                                   const ArgList &Args,
8164                                   const char *LinkingOutput) const {
8165   ArgStringList CmdArgs;
8166 
8167   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8168 
8169   // Add the "effective" target triple.
8170   CmdArgs.push_back("-target");
8171   CmdArgs.push_back(Args.MakeArgString(Triple.getTriple()));
8172 
8173   // Add the output file name.
8174   assert(Output.isFilename() && "Invalid output.");
8175   CmdArgs.push_back("-o");
8176   CmdArgs.push_back(Output.getFilename());
8177 
8178   // Add inputs.
8179   for (const InputInfo &I : Inputs) {
8180     assert(I.isFilename() && "Invalid input.");
8181     CmdArgs.push_back(I.getFilename());
8182   }
8183 
8184   C.addCommand(std::make_unique<Command>(
8185       JA, *this, ResponseFileSupport::None(),
8186       Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8187       CmdArgs, Inputs, Output));
8188 }
8189 
8190 void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
8191                                  const InputInfo &Output,
8192                                  const InputInfoList &Inputs,
8193                                  const ArgList &Args,
8194                                  const char *LinkingOutput) const {
8195   const Driver &D = getToolChain().getDriver();
8196   const llvm::Triple TheTriple = getToolChain().getTriple();
8197   auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
8198   ArgStringList CmdArgs;
8199 
8200   // Pass the CUDA path to the linker wrapper tool.
8201   for (auto &I : llvm::make_range(OpenMPTCRange.first, OpenMPTCRange.second)) {
8202     const ToolChain *TC = I.second;
8203     if (TC->getTriple().isNVPTX()) {
8204       CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
8205       if (CudaInstallation.isValid())
8206         CmdArgs.push_back(Args.MakeArgString(
8207             "--cuda-path=" + CudaInstallation.getInstallPath()));
8208       break;
8209     }
8210   }
8211 
8212   // Get the AMDGPU math libraries.
8213   // FIXME: This method is bad, remove once AMDGPU has a proper math library
8214   // (see AMDGCN::OpenMPLinker::constructLLVMLinkCommand).
8215   for (auto &I : llvm::make_range(OpenMPTCRange.first, OpenMPTCRange.second)) {
8216     const ToolChain *TC = I.second;
8217 
8218     if (!TC->getTriple().isAMDGPU() || Args.hasArg(options::OPT_nogpulib))
8219       continue;
8220 
8221     const ArgList &TCArgs = C.getArgsForToolChain(TC, "", Action::OFK_OpenMP);
8222     StringRef Arch = TCArgs.getLastArgValue(options::OPT_march_EQ);
8223     const toolchains::ROCMToolChain RocmTC(TC->getDriver(), TC->getTriple(),
8224                                            TCArgs);
8225 
8226     SmallVector<std::string, 12> BCLibs =
8227         RocmTC.getCommonDeviceLibNames(TCArgs, Arch.str());
8228 
8229     for (StringRef LibName : BCLibs)
8230       CmdArgs.push_back(Args.MakeArgString(
8231           "-target-library=" + Action::GetOffloadKindName(Action::OFK_OpenMP) +
8232           "-" + TC->getTripleString() + "-" + Arch + "=" + LibName));
8233   }
8234 
8235   if (D.isUsingLTO(/* IsOffload */ true)) {
8236     // Pass in target features for each toolchain.
8237     for (auto &I :
8238          llvm::make_range(OpenMPTCRange.first, OpenMPTCRange.second)) {
8239       const ToolChain *TC = I.second;
8240       const ArgList &TCArgs = C.getArgsForToolChain(TC, "", Action::OFK_OpenMP);
8241       ArgStringList FeatureArgs;
8242       TC->addClangTargetOptions(TCArgs, FeatureArgs, Action::OFK_OpenMP);
8243       auto FeatureIt = llvm::find(FeatureArgs, "-target-feature");
8244       if (FeatureIt != FeatureArgs.end())
8245         CmdArgs.push_back(
8246             Args.MakeArgString("-target-feature=" + TC->getTripleString() +
8247                                "=" + *(FeatureIt + 1)));
8248     }
8249 
8250     // Pass in the bitcode library to be linked during LTO.
8251     for (auto &I :
8252          llvm::make_range(OpenMPTCRange.first, OpenMPTCRange.second)) {
8253       const ToolChain *TC = I.second;
8254       if (!(TC->getTriple().isNVPTX() || TC->getTriple().isAMDGPU()))
8255         continue;
8256 
8257       const Driver &TCDriver = TC->getDriver();
8258       const ArgList &TCArgs = C.getArgsForToolChain(TC, "", Action::OFK_OpenMP);
8259       StringRef Arch = TCArgs.getLastArgValue(options::OPT_march_EQ);
8260 
8261       ArgStringList BitcodeLibrary;
8262       addOpenMPDeviceRTL(TCDriver, TCArgs, BitcodeLibrary, Arch,
8263                          TC->getTriple());
8264 
8265       if (!BitcodeLibrary.empty())
8266         CmdArgs.push_back(Args.MakeArgString(
8267             "-target-library=" +
8268             Action::GetOffloadKindName(Action::OFK_OpenMP) + "-" +
8269             TC->getTripleString() + "-" + Arch + "=" + BitcodeLibrary.back()));
8270     }
8271 
8272     // Pass in the optimization level to use for LTO.
8273     if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
8274       StringRef OOpt;
8275       if (A->getOption().matches(options::OPT_O4) ||
8276           A->getOption().matches(options::OPT_Ofast))
8277         OOpt = "3";
8278       else if (A->getOption().matches(options::OPT_O)) {
8279         OOpt = A->getValue();
8280         if (OOpt == "g")
8281           OOpt = "1";
8282         else if (OOpt == "s" || OOpt == "z")
8283           OOpt = "2";
8284       } else if (A->getOption().matches(options::OPT_O0))
8285         OOpt = "0";
8286       if (!OOpt.empty())
8287         CmdArgs.push_back(Args.MakeArgString(Twine("-opt-level=O") + OOpt));
8288     }
8289   }
8290 
8291   CmdArgs.push_back("-host-triple");
8292   CmdArgs.push_back(Args.MakeArgString(TheTriple.getTriple()));
8293   if (Args.hasArg(options::OPT_v))
8294     CmdArgs.push_back("-v");
8295 
8296   // Add debug information if present.
8297   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
8298     const Option &Opt = A->getOption();
8299     if (Opt.matches(options::OPT_gN_Group)) {
8300       if (Opt.matches(options::OPT_gline_directives_only) ||
8301           Opt.matches(options::OPT_gline_tables_only))
8302         CmdArgs.push_back("-gline-directives-only");
8303     } else
8304       CmdArgs.push_back("-g");
8305   }
8306 
8307   for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
8308     CmdArgs.push_back(Args.MakeArgString("-ptxas-args=" + A));
8309 
8310   // Forward remarks passes to the LLVM backend in the wrapper.
8311   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
8312     CmdArgs.push_back(
8313         Args.MakeArgString(Twine("-pass-remarks=") + A->getValue()));
8314   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
8315     CmdArgs.push_back(
8316         Args.MakeArgString(Twine("-pass-remarks-missed=") + A->getValue()));
8317   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
8318     CmdArgs.push_back(
8319         Args.MakeArgString(Twine("-pass-remarks-analysis=") + A->getValue()));
8320   if (Args.getLastArg(options::OPT_save_temps_EQ))
8321     CmdArgs.push_back("-save-temps");
8322 
8323   // Construct the link job so we can wrap around it.
8324   Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
8325   const auto &LinkCommand = C.getJobs().getJobs().back();
8326 
8327   // Add the linker arguments to be forwarded by the wrapper.
8328   CmdArgs.push_back("-linker-path");
8329   CmdArgs.push_back(LinkCommand->getExecutable());
8330   CmdArgs.push_back("--");
8331   for (const char *LinkArg : LinkCommand->getArguments())
8332     CmdArgs.push_back(LinkArg);
8333 
8334   const char *Exec =
8335       Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
8336 
8337   // Replace the executable and arguments of the link job with the
8338   // wrapper.
8339   LinkCommand->replaceExecutable(Exec);
8340   LinkCommand->replaceArguments(CmdArgs);
8341 }
8342