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