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