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