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