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