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