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