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