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