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