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