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 namespace {
1434 void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1435                       ArgStringList &CmdArgs) {
1436   const char *ABIName = nullptr;
1437   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1438     ABIName = A->getValue();
1439   else if (Triple.isOSDarwin())
1440     ABIName = "darwinpcs";
1441   else
1442     ABIName = "aapcs";
1443 
1444   CmdArgs.push_back("-target-abi");
1445   CmdArgs.push_back(ABIName);
1446 }
1447 }
1448 
1449 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1450                                  ArgStringList &CmdArgs) const {
1451   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1452 
1453   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1454       Args.hasArg(options::OPT_mkernel) ||
1455       Args.hasArg(options::OPT_fapple_kext))
1456     CmdArgs.push_back("-disable-red-zone");
1457 
1458   if (!Args.hasFlag(options::OPT_mimplicit_float,
1459                     options::OPT_mno_implicit_float, true))
1460     CmdArgs.push_back("-no-implicit-float");
1461 
1462   RenderAArch64ABI(Triple, Args, CmdArgs);
1463 
1464   if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1465                                options::OPT_mno_fix_cortex_a53_835769)) {
1466     CmdArgs.push_back("-mllvm");
1467     if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1468       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1469     else
1470       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1471   } else if (Triple.isAndroid()) {
1472     // Enabled A53 errata (835769) workaround by default on android
1473     CmdArgs.push_back("-mllvm");
1474     CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1475   }
1476 
1477   // Forward the -mglobal-merge option for explicit control over the pass.
1478   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1479                                options::OPT_mno_global_merge)) {
1480     CmdArgs.push_back("-mllvm");
1481     if (A->getOption().matches(options::OPT_mno_global_merge))
1482       CmdArgs.push_back("-aarch64-enable-global-merge=false");
1483     else
1484       CmdArgs.push_back("-aarch64-enable-global-merge=true");
1485   }
1486 
1487   if (Arg *A = Args.getLastArg(options::OPT_msign_return_address)) {
1488     CmdArgs.push_back(
1489         Args.MakeArgString(Twine("-msign-return-address=") + A->getValue()));
1490   }
1491 }
1492 
1493 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1494                               ArgStringList &CmdArgs) const {
1495   const Driver &D = getToolChain().getDriver();
1496   StringRef CPUName;
1497   StringRef ABIName;
1498   const llvm::Triple &Triple = getToolChain().getTriple();
1499   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1500 
1501   CmdArgs.push_back("-target-abi");
1502   CmdArgs.push_back(ABIName.data());
1503 
1504   mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1505   if (ABI == mips::FloatABI::Soft) {
1506     // Floating point operations and argument passing are soft.
1507     CmdArgs.push_back("-msoft-float");
1508     CmdArgs.push_back("-mfloat-abi");
1509     CmdArgs.push_back("soft");
1510   } else {
1511     // Floating point operations and argument passing are hard.
1512     assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1513     CmdArgs.push_back("-mfloat-abi");
1514     CmdArgs.push_back("hard");
1515   }
1516 
1517   if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1518     if (A->getOption().matches(options::OPT_mxgot)) {
1519       CmdArgs.push_back("-mllvm");
1520       CmdArgs.push_back("-mxgot");
1521     }
1522   }
1523 
1524   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1525                                options::OPT_mno_ldc1_sdc1)) {
1526     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1527       CmdArgs.push_back("-mllvm");
1528       CmdArgs.push_back("-mno-ldc1-sdc1");
1529     }
1530   }
1531 
1532   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1533                                options::OPT_mno_check_zero_division)) {
1534     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1535       CmdArgs.push_back("-mllvm");
1536       CmdArgs.push_back("-mno-check-zero-division");
1537     }
1538   }
1539 
1540   if (Arg *A = Args.getLastArg(options::OPT_G)) {
1541     StringRef v = A->getValue();
1542     CmdArgs.push_back("-mllvm");
1543     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1544     A->claim();
1545   }
1546 
1547   Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1548   Arg *ABICalls =
1549       Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1550 
1551   // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1552   // -mgpopt is the default for static, -fno-pic environments but these two
1553   // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1554   // the only case where -mllvm -mgpopt is passed.
1555   // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1556   //       passed explicitly when compiling something with -mabicalls
1557   //       (implictly) in affect. Currently the warning is in the backend.
1558   //
1559   // When the ABI in use is  N64, we also need to determine the PIC mode that
1560   // is in use, as -fno-pic for N64 implies -mno-abicalls.
1561   bool NoABICalls =
1562       ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1563 
1564   llvm::Reloc::Model RelocationModel;
1565   unsigned PICLevel;
1566   bool IsPIE;
1567   std::tie(RelocationModel, PICLevel, IsPIE) =
1568       ParsePICArgs(getToolChain(), Args);
1569 
1570   NoABICalls = NoABICalls ||
1571                (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1572 
1573   bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1574   // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1575   if (NoABICalls && (!GPOpt || WantGPOpt)) {
1576     CmdArgs.push_back("-mllvm");
1577     CmdArgs.push_back("-mgpopt");
1578 
1579     Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1580                                       options::OPT_mno_local_sdata);
1581     Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1582                                        options::OPT_mno_extern_sdata);
1583     Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1584                                         options::OPT_mno_embedded_data);
1585     if (LocalSData) {
1586       CmdArgs.push_back("-mllvm");
1587       if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1588         CmdArgs.push_back("-mlocal-sdata=1");
1589       } else {
1590         CmdArgs.push_back("-mlocal-sdata=0");
1591       }
1592       LocalSData->claim();
1593     }
1594 
1595     if (ExternSData) {
1596       CmdArgs.push_back("-mllvm");
1597       if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1598         CmdArgs.push_back("-mextern-sdata=1");
1599       } else {
1600         CmdArgs.push_back("-mextern-sdata=0");
1601       }
1602       ExternSData->claim();
1603     }
1604 
1605     if (EmbeddedData) {
1606       CmdArgs.push_back("-mllvm");
1607       if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1608         CmdArgs.push_back("-membedded-data=1");
1609       } else {
1610         CmdArgs.push_back("-membedded-data=0");
1611       }
1612       EmbeddedData->claim();
1613     }
1614 
1615   } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1616     D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1617 
1618   if (GPOpt)
1619     GPOpt->claim();
1620 
1621   if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1622     StringRef Val = StringRef(A->getValue());
1623     if (mips::hasCompactBranches(CPUName)) {
1624       if (Val == "never" || Val == "always" || Val == "optimal") {
1625         CmdArgs.push_back("-mllvm");
1626         CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1627       } else
1628         D.Diag(diag::err_drv_unsupported_option_argument)
1629             << A->getOption().getName() << Val;
1630     } else
1631       D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1632   }
1633 }
1634 
1635 void Clang::AddPPCTargetArgs(const ArgList &Args,
1636                              ArgStringList &CmdArgs) const {
1637   // Select the ABI to use.
1638   const char *ABIName = nullptr;
1639   if (getToolChain().getTriple().isOSLinux())
1640     switch (getToolChain().getArch()) {
1641     case llvm::Triple::ppc64: {
1642       // When targeting a processor that supports QPX, or if QPX is
1643       // specifically enabled, default to using the ABI that supports QPX (so
1644       // long as it is not specifically disabled).
1645       bool HasQPX = false;
1646       if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1647         HasQPX = A->getValue() == StringRef("a2q");
1648       HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1649       if (HasQPX) {
1650         ABIName = "elfv1-qpx";
1651         break;
1652       }
1653 
1654       ABIName = "elfv1";
1655       break;
1656     }
1657     case llvm::Triple::ppc64le:
1658       ABIName = "elfv2";
1659       break;
1660     default:
1661       break;
1662     }
1663 
1664   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1665     // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1666     // the option if given as we don't have backend support for any targets
1667     // that don't use the altivec abi.
1668     if (StringRef(A->getValue()) != "altivec")
1669       ABIName = A->getValue();
1670 
1671   ppc::FloatABI FloatABI =
1672       ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1673 
1674   if (FloatABI == ppc::FloatABI::Soft) {
1675     // Floating point operations and argument passing are soft.
1676     CmdArgs.push_back("-msoft-float");
1677     CmdArgs.push_back("-mfloat-abi");
1678     CmdArgs.push_back("soft");
1679   } else {
1680     // Floating point operations and argument passing are hard.
1681     assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1682     CmdArgs.push_back("-mfloat-abi");
1683     CmdArgs.push_back("hard");
1684   }
1685 
1686   if (ABIName) {
1687     CmdArgs.push_back("-target-abi");
1688     CmdArgs.push_back(ABIName);
1689   }
1690 }
1691 
1692 void Clang::AddRISCVTargetArgs(const ArgList &Args,
1693                                ArgStringList &CmdArgs) const {
1694   // FIXME: currently defaults to the soft-float ABIs. Will need to be
1695   // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
1696   const char *ABIName = nullptr;
1697   const llvm::Triple &Triple = getToolChain().getTriple();
1698   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1699     ABIName = A->getValue();
1700   else if (Triple.getArch() == llvm::Triple::riscv32)
1701     ABIName = "ilp32";
1702   else if (Triple.getArch() == llvm::Triple::riscv64)
1703     ABIName = "lp64";
1704   else
1705     llvm_unreachable("Unexpected triple!");
1706 
1707   CmdArgs.push_back("-target-abi");
1708   CmdArgs.push_back(ABIName);
1709 }
1710 
1711 void Clang::AddSparcTargetArgs(const ArgList &Args,
1712                                ArgStringList &CmdArgs) const {
1713   sparc::FloatABI FloatABI =
1714       sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1715 
1716   if (FloatABI == sparc::FloatABI::Soft) {
1717     // Floating point operations and argument passing are soft.
1718     CmdArgs.push_back("-msoft-float");
1719     CmdArgs.push_back("-mfloat-abi");
1720     CmdArgs.push_back("soft");
1721   } else {
1722     // Floating point operations and argument passing are hard.
1723     assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1724     CmdArgs.push_back("-mfloat-abi");
1725     CmdArgs.push_back("hard");
1726   }
1727 }
1728 
1729 void Clang::AddSystemZTargetArgs(const ArgList &Args,
1730                                  ArgStringList &CmdArgs) const {
1731   if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1732     CmdArgs.push_back("-mbackchain");
1733 }
1734 
1735 void Clang::AddX86TargetArgs(const ArgList &Args,
1736                              ArgStringList &CmdArgs) const {
1737   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1738       Args.hasArg(options::OPT_mkernel) ||
1739       Args.hasArg(options::OPT_fapple_kext))
1740     CmdArgs.push_back("-disable-red-zone");
1741 
1742   if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1743                     options::OPT_mno_tls_direct_seg_refs, true))
1744     CmdArgs.push_back("-mno-tls-direct-seg-refs");
1745 
1746   // Default to avoid implicit floating-point for kernel/kext code, but allow
1747   // that to be overridden with -mno-soft-float.
1748   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1749                           Args.hasArg(options::OPT_fapple_kext));
1750   if (Arg *A = Args.getLastArg(
1751           options::OPT_msoft_float, options::OPT_mno_soft_float,
1752           options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1753     const Option &O = A->getOption();
1754     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1755                        O.matches(options::OPT_msoft_float));
1756   }
1757   if (NoImplicitFloat)
1758     CmdArgs.push_back("-no-implicit-float");
1759 
1760   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1761     StringRef Value = A->getValue();
1762     if (Value == "intel" || Value == "att") {
1763       CmdArgs.push_back("-mllvm");
1764       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1765     } else {
1766       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1767           << A->getOption().getName() << Value;
1768     }
1769   } else if (getToolChain().getDriver().IsCLMode()) {
1770     CmdArgs.push_back("-mllvm");
1771     CmdArgs.push_back("-x86-asm-syntax=intel");
1772   }
1773 
1774   // Set flags to support MCU ABI.
1775   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1776     CmdArgs.push_back("-mfloat-abi");
1777     CmdArgs.push_back("soft");
1778     CmdArgs.push_back("-mstack-alignment=4");
1779   }
1780 }
1781 
1782 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1783                                  ArgStringList &CmdArgs) const {
1784   CmdArgs.push_back("-mqdsp6-compat");
1785   CmdArgs.push_back("-Wreturn-type");
1786 
1787   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
1788     CmdArgs.push_back("-mllvm");
1789     CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1790                                          Twine(G.getValue())));
1791   }
1792 
1793   if (!Args.hasArg(options::OPT_fno_short_enums))
1794     CmdArgs.push_back("-fshort-enums");
1795   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1796     CmdArgs.push_back("-mllvm");
1797     CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1798   }
1799   CmdArgs.push_back("-mllvm");
1800   CmdArgs.push_back("-machine-sink-split=0");
1801 }
1802 
1803 void Clang::AddLanaiTargetArgs(const ArgList &Args,
1804                                ArgStringList &CmdArgs) const {
1805   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1806     StringRef CPUName = A->getValue();
1807 
1808     CmdArgs.push_back("-target-cpu");
1809     CmdArgs.push_back(Args.MakeArgString(CPUName));
1810   }
1811   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1812     StringRef Value = A->getValue();
1813     // Only support mregparm=4 to support old usage. Report error for all other
1814     // cases.
1815     int Mregparm;
1816     if (Value.getAsInteger(10, Mregparm)) {
1817       if (Mregparm != 4) {
1818         getToolChain().getDriver().Diag(
1819             diag::err_drv_unsupported_option_argument)
1820             << A->getOption().getName() << Value;
1821       }
1822     }
1823   }
1824 }
1825 
1826 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1827                                      ArgStringList &CmdArgs) const {
1828   // Default to "hidden" visibility.
1829   if (!Args.hasArg(options::OPT_fvisibility_EQ,
1830                    options::OPT_fvisibility_ms_compat)) {
1831     CmdArgs.push_back("-fvisibility");
1832     CmdArgs.push_back("hidden");
1833   }
1834 }
1835 
1836 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1837                                     StringRef Target, const InputInfo &Output,
1838                                     const InputInfo &Input, const ArgList &Args) const {
1839   // If this is a dry run, do not create the compilation database file.
1840   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1841     return;
1842 
1843   using llvm::yaml::escape;
1844   const Driver &D = getToolChain().getDriver();
1845 
1846   if (!CompilationDatabase) {
1847     std::error_code EC;
1848     auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1849     if (EC) {
1850       D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1851                                                        << EC.message();
1852       return;
1853     }
1854     CompilationDatabase = std::move(File);
1855   }
1856   auto &CDB = *CompilationDatabase;
1857   SmallString<128> Buf;
1858   if (llvm::sys::fs::current_path(Buf))
1859     Buf = ".";
1860   CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1861   CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1862   CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1863   CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1864   Buf = "-x";
1865   Buf += types::getTypeName(Input.getType());
1866   CDB << ", \"" << escape(Buf) << "\"";
1867   if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1868     Buf = "--sysroot=";
1869     Buf += D.SysRoot;
1870     CDB << ", \"" << escape(Buf) << "\"";
1871   }
1872   CDB << ", \"" << escape(Input.getFilename()) << "\"";
1873   for (auto &A: Args) {
1874     auto &O = A->getOption();
1875     // Skip language selection, which is positional.
1876     if (O.getID() == options::OPT_x)
1877       continue;
1878     // Skip writing dependency output and the compilation database itself.
1879     if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1880       continue;
1881     // Skip inputs.
1882     if (O.getKind() == Option::InputClass)
1883       continue;
1884     // All other arguments are quoted and appended.
1885     ArgStringList ASL;
1886     A->render(Args, ASL);
1887     for (auto &it: ASL)
1888       CDB << ", \"" << escape(it) << "\"";
1889   }
1890   Buf = "--target=";
1891   Buf += Target;
1892   CDB << ", \"" << escape(Buf) << "\"]},\n";
1893 }
1894 
1895 static void CollectArgsForIntegratedAssembler(Compilation &C,
1896                                               const ArgList &Args,
1897                                               ArgStringList &CmdArgs,
1898                                               const Driver &D) {
1899   if (UseRelaxAll(C, Args))
1900     CmdArgs.push_back("-mrelax-all");
1901 
1902   // Only default to -mincremental-linker-compatible if we think we are
1903   // targeting the MSVC linker.
1904   bool DefaultIncrementalLinkerCompatible =
1905       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1906   if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1907                    options::OPT_mno_incremental_linker_compatible,
1908                    DefaultIncrementalLinkerCompatible))
1909     CmdArgs.push_back("-mincremental-linker-compatible");
1910 
1911   switch (C.getDefaultToolChain().getArch()) {
1912   case llvm::Triple::arm:
1913   case llvm::Triple::armeb:
1914   case llvm::Triple::thumb:
1915   case llvm::Triple::thumbeb:
1916     if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1917       StringRef Value = A->getValue();
1918       if (Value == "always" || Value == "never" || Value == "arm" ||
1919           Value == "thumb") {
1920         CmdArgs.push_back("-mllvm");
1921         CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1922       } else {
1923         D.Diag(diag::err_drv_unsupported_option_argument)
1924             << A->getOption().getName() << Value;
1925       }
1926     }
1927     break;
1928   default:
1929     break;
1930   }
1931 
1932   // When passing -I arguments to the assembler we sometimes need to
1933   // unconditionally take the next argument.  For example, when parsing
1934   // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1935   // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1936   // arg after parsing the '-I' arg.
1937   bool TakeNextArg = false;
1938 
1939   bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
1940   const char *MipsTargetFeature = nullptr;
1941   for (const Arg *A :
1942        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1943     A->claim();
1944 
1945     for (StringRef Value : A->getValues()) {
1946       if (TakeNextArg) {
1947         CmdArgs.push_back(Value.data());
1948         TakeNextArg = false;
1949         continue;
1950       }
1951 
1952       if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1953           Value == "-mbig-obj")
1954         continue; // LLVM handles bigobj automatically
1955 
1956       switch (C.getDefaultToolChain().getArch()) {
1957       default:
1958         break;
1959       case llvm::Triple::thumb:
1960       case llvm::Triple::thumbeb:
1961       case llvm::Triple::arm:
1962       case llvm::Triple::armeb:
1963         if (Value == "-mthumb")
1964           // -mthumb has already been processed in ComputeLLVMTriple()
1965           // recognize but skip over here.
1966           continue;
1967         break;
1968       case llvm::Triple::mips:
1969       case llvm::Triple::mipsel:
1970       case llvm::Triple::mips64:
1971       case llvm::Triple::mips64el:
1972         if (Value == "--trap") {
1973           CmdArgs.push_back("-target-feature");
1974           CmdArgs.push_back("+use-tcc-in-div");
1975           continue;
1976         }
1977         if (Value == "--break") {
1978           CmdArgs.push_back("-target-feature");
1979           CmdArgs.push_back("-use-tcc-in-div");
1980           continue;
1981         }
1982         if (Value.startswith("-msoft-float")) {
1983           CmdArgs.push_back("-target-feature");
1984           CmdArgs.push_back("+soft-float");
1985           continue;
1986         }
1987         if (Value.startswith("-mhard-float")) {
1988           CmdArgs.push_back("-target-feature");
1989           CmdArgs.push_back("-soft-float");
1990           continue;
1991         }
1992 
1993         MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1994                                 .Case("-mips1", "+mips1")
1995                                 .Case("-mips2", "+mips2")
1996                                 .Case("-mips3", "+mips3")
1997                                 .Case("-mips4", "+mips4")
1998                                 .Case("-mips5", "+mips5")
1999                                 .Case("-mips32", "+mips32")
2000                                 .Case("-mips32r2", "+mips32r2")
2001                                 .Case("-mips32r3", "+mips32r3")
2002                                 .Case("-mips32r5", "+mips32r5")
2003                                 .Case("-mips32r6", "+mips32r6")
2004                                 .Case("-mips64", "+mips64")
2005                                 .Case("-mips64r2", "+mips64r2")
2006                                 .Case("-mips64r3", "+mips64r3")
2007                                 .Case("-mips64r5", "+mips64r5")
2008                                 .Case("-mips64r6", "+mips64r6")
2009                                 .Default(nullptr);
2010         if (MipsTargetFeature)
2011           continue;
2012       }
2013 
2014       if (Value == "-force_cpusubtype_ALL") {
2015         // Do nothing, this is the default and we don't support anything else.
2016       } else if (Value == "-L") {
2017         CmdArgs.push_back("-msave-temp-labels");
2018       } else if (Value == "--fatal-warnings") {
2019         CmdArgs.push_back("-massembler-fatal-warnings");
2020       } else if (Value == "--noexecstack") {
2021         CmdArgs.push_back("-mnoexecstack");
2022       } else if (Value.startswith("-compress-debug-sections") ||
2023                  Value.startswith("--compress-debug-sections") ||
2024                  Value == "-nocompress-debug-sections" ||
2025                  Value == "--nocompress-debug-sections") {
2026         CmdArgs.push_back(Value.data());
2027       } else if (Value == "-mrelax-relocations=yes" ||
2028                  Value == "--mrelax-relocations=yes") {
2029         UseRelaxRelocations = true;
2030       } else if (Value == "-mrelax-relocations=no" ||
2031                  Value == "--mrelax-relocations=no") {
2032         UseRelaxRelocations = false;
2033       } else if (Value.startswith("-I")) {
2034         CmdArgs.push_back(Value.data());
2035         // We need to consume the next argument if the current arg is a plain
2036         // -I. The next arg will be the include directory.
2037         if (Value == "-I")
2038           TakeNextArg = true;
2039       } else if (Value.startswith("-gdwarf-")) {
2040         // "-gdwarf-N" options are not cc1as options.
2041         unsigned DwarfVersion = DwarfVersionNum(Value);
2042         if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2043           CmdArgs.push_back(Value.data());
2044         } else {
2045           RenderDebugEnablingArgs(Args, CmdArgs,
2046                                   codegenoptions::LimitedDebugInfo,
2047                                   DwarfVersion, llvm::DebuggerKind::Default);
2048         }
2049       } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2050                  Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2051         // Do nothing, we'll validate it later.
2052       } else if (Value == "-defsym") {
2053           if (A->getNumValues() != 2) {
2054             D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2055             break;
2056           }
2057           const char *S = A->getValue(1);
2058           auto Pair = StringRef(S).split('=');
2059           auto Sym = Pair.first;
2060           auto SVal = Pair.second;
2061 
2062           if (Sym.empty() || SVal.empty()) {
2063             D.Diag(diag::err_drv_defsym_invalid_format) << S;
2064             break;
2065           }
2066           int64_t IVal;
2067           if (SVal.getAsInteger(0, IVal)) {
2068             D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2069             break;
2070           }
2071           CmdArgs.push_back(Value.data());
2072           TakeNextArg = true;
2073       } else {
2074         D.Diag(diag::err_drv_unsupported_option_argument)
2075             << A->getOption().getName() << Value;
2076       }
2077     }
2078   }
2079   if (UseRelaxRelocations)
2080     CmdArgs.push_back("--mrelax-relocations");
2081   if (MipsTargetFeature != nullptr) {
2082     CmdArgs.push_back("-target-feature");
2083     CmdArgs.push_back(MipsTargetFeature);
2084   }
2085 }
2086 
2087 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2088                                        bool OFastEnabled, const ArgList &Args,
2089                                        ArgStringList &CmdArgs) {
2090   // Handle various floating point optimization flags, mapping them to the
2091   // appropriate LLVM code generation flags. This is complicated by several
2092   // "umbrella" flags, so we do this by stepping through the flags incrementally
2093   // adjusting what we think is enabled/disabled, then at the end setting the
2094   // LLVM flags based on the final state.
2095   bool HonorINFs = true;
2096   bool HonorNaNs = true;
2097   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2098   bool MathErrno = TC.IsMathErrnoDefault();
2099   bool AssociativeMath = false;
2100   bool ReciprocalMath = false;
2101   bool SignedZeros = true;
2102   bool TrappingMath = true;
2103   StringRef DenormalFPMath = "";
2104   StringRef FPContract = "";
2105 
2106   if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2107     CmdArgs.push_back("-mlimit-float-precision");
2108     CmdArgs.push_back(A->getValue());
2109   }
2110 
2111   for (const Arg *A : Args) {
2112     switch (A->getOption().getID()) {
2113     // If this isn't an FP option skip the claim below
2114     default: continue;
2115 
2116     // Options controlling individual features
2117     case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
2118     case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
2119     case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
2120     case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
2121     case options::OPT_fmath_errno:          MathErrno = true;         break;
2122     case options::OPT_fno_math_errno:       MathErrno = false;        break;
2123     case options::OPT_fassociative_math:    AssociativeMath = true;   break;
2124     case options::OPT_fno_associative_math: AssociativeMath = false;  break;
2125     case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
2126     case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
2127     case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
2128     case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
2129     case options::OPT_ftrapping_math:       TrappingMath = true;      break;
2130     case options::OPT_fno_trapping_math:    TrappingMath = false;     break;
2131 
2132     case options::OPT_fdenormal_fp_math_EQ:
2133       DenormalFPMath = A->getValue();
2134       break;
2135 
2136     // Validate and pass through -fp-contract option.
2137     case options::OPT_ffp_contract: {
2138       StringRef Val = A->getValue();
2139       if (Val == "fast" || Val == "on" || Val == "off")
2140         FPContract = Val;
2141       else
2142         D.Diag(diag::err_drv_unsupported_option_argument)
2143             << A->getOption().getName() << Val;
2144       break;
2145     }
2146 
2147     case options::OPT_ffinite_math_only:
2148       HonorINFs = false;
2149       HonorNaNs = false;
2150       break;
2151     case options::OPT_fno_finite_math_only:
2152       HonorINFs = true;
2153       HonorNaNs = true;
2154       break;
2155 
2156     case options::OPT_funsafe_math_optimizations:
2157       AssociativeMath = true;
2158       ReciprocalMath = true;
2159       SignedZeros = false;
2160       TrappingMath = false;
2161       break;
2162     case options::OPT_fno_unsafe_math_optimizations:
2163       AssociativeMath = false;
2164       ReciprocalMath = false;
2165       SignedZeros = true;
2166       TrappingMath = true;
2167       // -fno_unsafe_math_optimizations restores default denormal handling
2168       DenormalFPMath = "";
2169       break;
2170 
2171     case options::OPT_Ofast:
2172       // If -Ofast is the optimization level, then -ffast-math should be enabled
2173       if (!OFastEnabled)
2174         continue;
2175       LLVM_FALLTHROUGH;
2176     case options::OPT_ffast_math:
2177       HonorINFs = false;
2178       HonorNaNs = false;
2179       MathErrno = false;
2180       AssociativeMath = true;
2181       ReciprocalMath = true;
2182       SignedZeros = false;
2183       TrappingMath = false;
2184       // If fast-math is set then set the fp-contract mode to fast.
2185       FPContract = "fast";
2186       break;
2187     case options::OPT_fno_fast_math:
2188       HonorINFs = true;
2189       HonorNaNs = true;
2190       // Turning on -ffast-math (with either flag) removes the need for
2191       // MathErrno. However, turning *off* -ffast-math merely restores the
2192       // toolchain default (which may be false).
2193       MathErrno = TC.IsMathErrnoDefault();
2194       AssociativeMath = false;
2195       ReciprocalMath = false;
2196       SignedZeros = true;
2197       TrappingMath = true;
2198       // -fno_fast_math restores default denormal and fpcontract handling
2199       DenormalFPMath = "";
2200       FPContract = "";
2201       break;
2202     }
2203 
2204     // If we handled this option claim it
2205     A->claim();
2206   }
2207 
2208   if (!HonorINFs)
2209     CmdArgs.push_back("-menable-no-infs");
2210 
2211   if (!HonorNaNs)
2212     CmdArgs.push_back("-menable-no-nans");
2213 
2214   if (MathErrno)
2215     CmdArgs.push_back("-fmath-errno");
2216 
2217   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2218       !TrappingMath)
2219     CmdArgs.push_back("-menable-unsafe-fp-math");
2220 
2221   if (!SignedZeros)
2222     CmdArgs.push_back("-fno-signed-zeros");
2223 
2224   if (AssociativeMath && !SignedZeros && !TrappingMath)
2225     CmdArgs.push_back("-mreassociate");
2226 
2227   if (ReciprocalMath)
2228     CmdArgs.push_back("-freciprocal-math");
2229 
2230   if (!TrappingMath)
2231     CmdArgs.push_back("-fno-trapping-math");
2232 
2233   if (!DenormalFPMath.empty())
2234     CmdArgs.push_back(
2235         Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2236 
2237   if (!FPContract.empty())
2238     CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2239 
2240   ParseMRecip(D, Args, CmdArgs);
2241 
2242   // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2243   // individual features enabled by -ffast-math instead of the option itself as
2244   // that's consistent with gcc's behaviour.
2245   if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2246       ReciprocalMath && !SignedZeros && !TrappingMath)
2247     CmdArgs.push_back("-ffast-math");
2248 
2249   // Handle __FINITE_MATH_ONLY__ similarly.
2250   if (!HonorINFs && !HonorNaNs)
2251     CmdArgs.push_back("-ffinite-math-only");
2252 
2253   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2254     CmdArgs.push_back("-mfpmath");
2255     CmdArgs.push_back(A->getValue());
2256   }
2257 
2258   // Disable a codegen optimization for floating-point casts.
2259   if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2260                    options::OPT_fstrict_float_cast_overflow, false))
2261     CmdArgs.push_back("-fno-strict-float-cast-overflow");
2262 }
2263 
2264 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2265                                   const llvm::Triple &Triple,
2266                                   const InputInfo &Input) {
2267   // Enable region store model by default.
2268   CmdArgs.push_back("-analyzer-store=region");
2269 
2270   // Treat blocks as analysis entry points.
2271   CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2272 
2273   // Add default argument set.
2274   if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2275     CmdArgs.push_back("-analyzer-checker=core");
2276     CmdArgs.push_back("-analyzer-checker=apiModeling");
2277 
2278     if (!Triple.isWindowsMSVCEnvironment()) {
2279       CmdArgs.push_back("-analyzer-checker=unix");
2280     } else {
2281       // Enable "unix" checkers that also work on Windows.
2282       CmdArgs.push_back("-analyzer-checker=unix.API");
2283       CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2284       CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2285       CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2286       CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2287       CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2288     }
2289 
2290     // Disable some unix checkers for PS4.
2291     if (Triple.isPS4CPU()) {
2292       CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2293       CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2294     }
2295 
2296     if (Triple.isOSDarwin())
2297       CmdArgs.push_back("-analyzer-checker=osx");
2298 
2299     CmdArgs.push_back("-analyzer-checker=deadcode");
2300 
2301     if (types::isCXX(Input.getType()))
2302       CmdArgs.push_back("-analyzer-checker=cplusplus");
2303 
2304     if (!Triple.isPS4CPU()) {
2305       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2306       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2307       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2308       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2309       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2310       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2311     }
2312 
2313     // Default nullability checks.
2314     CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2315     CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2316   }
2317 
2318   // Set the output format. The default is plist, for (lame) historical reasons.
2319   CmdArgs.push_back("-analyzer-output");
2320   if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2321     CmdArgs.push_back(A->getValue());
2322   else
2323     CmdArgs.push_back("plist");
2324 
2325   // Disable the presentation of standard compiler warnings when using
2326   // --analyze.  We only want to show static analyzer diagnostics or frontend
2327   // errors.
2328   CmdArgs.push_back("-w");
2329 
2330   // Add -Xanalyzer arguments when running as analyzer.
2331   Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2332 }
2333 
2334 static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
2335                              ArgStringList &CmdArgs, bool KernelOrKext) {
2336   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2337 
2338   // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2339   // doesn't even have a stack!
2340   if (EffectiveTriple.isNVPTX())
2341     return;
2342 
2343   // -stack-protector=0 is default.
2344   unsigned StackProtectorLevel = 0;
2345   unsigned DefaultStackProtectorLevel =
2346       TC.GetDefaultStackProtectorLevel(KernelOrKext);
2347 
2348   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2349                                options::OPT_fstack_protector_all,
2350                                options::OPT_fstack_protector_strong,
2351                                options::OPT_fstack_protector)) {
2352     if (A->getOption().matches(options::OPT_fstack_protector))
2353       StackProtectorLevel =
2354           std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2355     else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2356       StackProtectorLevel = LangOptions::SSPStrong;
2357     else if (A->getOption().matches(options::OPT_fstack_protector_all))
2358       StackProtectorLevel = LangOptions::SSPReq;
2359   } else {
2360     StackProtectorLevel = DefaultStackProtectorLevel;
2361   }
2362 
2363   if (StackProtectorLevel) {
2364     CmdArgs.push_back("-stack-protector");
2365     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2366   }
2367 
2368   // --param ssp-buffer-size=
2369   for (const Arg *A : Args.filtered(options::OPT__param)) {
2370     StringRef Str(A->getValue());
2371     if (Str.startswith("ssp-buffer-size=")) {
2372       if (StackProtectorLevel) {
2373         CmdArgs.push_back("-stack-protector-buffer-size");
2374         // FIXME: Verify the argument is a valid integer.
2375         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2376       }
2377       A->claim();
2378     }
2379   }
2380 }
2381 
2382 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2383   const unsigned ForwardedArguments[] = {
2384       options::OPT_cl_opt_disable,
2385       options::OPT_cl_strict_aliasing,
2386       options::OPT_cl_single_precision_constant,
2387       options::OPT_cl_finite_math_only,
2388       options::OPT_cl_kernel_arg_info,
2389       options::OPT_cl_unsafe_math_optimizations,
2390       options::OPT_cl_fast_relaxed_math,
2391       options::OPT_cl_mad_enable,
2392       options::OPT_cl_no_signed_zeros,
2393       options::OPT_cl_denorms_are_zero,
2394       options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
2395       options::OPT_cl_uniform_work_group_size
2396   };
2397 
2398   if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2399     std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2400     CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2401   }
2402 
2403   for (const auto &Arg : ForwardedArguments)
2404     if (const auto *A = Args.getLastArg(Arg))
2405       CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2406 }
2407 
2408 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2409                                         ArgStringList &CmdArgs) {
2410   bool ARCMTEnabled = false;
2411   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2412     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2413                                        options::OPT_ccc_arcmt_modify,
2414                                        options::OPT_ccc_arcmt_migrate)) {
2415       ARCMTEnabled = true;
2416       switch (A->getOption().getID()) {
2417       default: llvm_unreachable("missed a case");
2418       case options::OPT_ccc_arcmt_check:
2419         CmdArgs.push_back("-arcmt-check");
2420         break;
2421       case options::OPT_ccc_arcmt_modify:
2422         CmdArgs.push_back("-arcmt-modify");
2423         break;
2424       case options::OPT_ccc_arcmt_migrate:
2425         CmdArgs.push_back("-arcmt-migrate");
2426         CmdArgs.push_back("-mt-migrate-directory");
2427         CmdArgs.push_back(A->getValue());
2428 
2429         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2430         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2431         break;
2432       }
2433     }
2434   } else {
2435     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2436     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2437     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2438   }
2439 
2440   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2441     if (ARCMTEnabled)
2442       D.Diag(diag::err_drv_argument_not_allowed_with)
2443           << A->getAsString(Args) << "-ccc-arcmt-migrate";
2444 
2445     CmdArgs.push_back("-mt-migrate-directory");
2446     CmdArgs.push_back(A->getValue());
2447 
2448     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2449                      options::OPT_objcmt_migrate_subscripting,
2450                      options::OPT_objcmt_migrate_property)) {
2451       // None specified, means enable them all.
2452       CmdArgs.push_back("-objcmt-migrate-literals");
2453       CmdArgs.push_back("-objcmt-migrate-subscripting");
2454       CmdArgs.push_back("-objcmt-migrate-property");
2455     } else {
2456       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2457       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2458       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2459     }
2460   } else {
2461     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2462     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2463     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2464     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2465     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2466     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2467     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2468     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2469     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2470     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2471     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2472     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2473     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2474     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2475     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2476     Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2477   }
2478 }
2479 
2480 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2481                                  const ArgList &Args, ArgStringList &CmdArgs) {
2482   // -fbuiltin is default unless -mkernel is used.
2483   bool UseBuiltins =
2484       Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2485                    !Args.hasArg(options::OPT_mkernel));
2486   if (!UseBuiltins)
2487     CmdArgs.push_back("-fno-builtin");
2488 
2489   // -ffreestanding implies -fno-builtin.
2490   if (Args.hasArg(options::OPT_ffreestanding))
2491     UseBuiltins = false;
2492 
2493   // Process the -fno-builtin-* options.
2494   for (const auto &Arg : Args) {
2495     const Option &O = Arg->getOption();
2496     if (!O.matches(options::OPT_fno_builtin_))
2497       continue;
2498 
2499     Arg->claim();
2500 
2501     // If -fno-builtin is specified, then there's no need to pass the option to
2502     // the frontend.
2503     if (!UseBuiltins)
2504       continue;
2505 
2506     StringRef FuncName = Arg->getValue();
2507     CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2508   }
2509 
2510   // le32-specific flags:
2511   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
2512   //                     by default.
2513   if (TC.getArch() == llvm::Triple::le32)
2514     CmdArgs.push_back("-fno-math-builtin");
2515 }
2516 
2517 void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2518   llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2519   llvm::sys::path::append(Result, "org.llvm.clang.");
2520   appendUserToPath(Result);
2521   llvm::sys::path::append(Result, "ModuleCache");
2522 }
2523 
2524 static void RenderModulesOptions(Compilation &C, const Driver &D,
2525                                  const ArgList &Args, const InputInfo &Input,
2526                                  const InputInfo &Output,
2527                                  ArgStringList &CmdArgs, bool &HaveModules) {
2528   // -fmodules enables the use of precompiled modules (off by default).
2529   // Users can pass -fno-cxx-modules to turn off modules support for
2530   // C++/Objective-C++ programs.
2531   bool HaveClangModules = false;
2532   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2533     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2534                                      options::OPT_fno_cxx_modules, true);
2535     if (AllowedInCXX || !types::isCXX(Input.getType())) {
2536       CmdArgs.push_back("-fmodules");
2537       HaveClangModules = true;
2538     }
2539   }
2540 
2541   HaveModules = HaveClangModules;
2542   if (Args.hasArg(options::OPT_fmodules_ts)) {
2543     CmdArgs.push_back("-fmodules-ts");
2544     HaveModules = true;
2545   }
2546 
2547   // -fmodule-maps enables implicit reading of module map files. By default,
2548   // this is enabled if we are using Clang's flavor of precompiled modules.
2549   if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2550                    options::OPT_fno_implicit_module_maps, HaveClangModules))
2551     CmdArgs.push_back("-fimplicit-module-maps");
2552 
2553   // -fmodules-decluse checks that modules used are declared so (off by default)
2554   if (Args.hasFlag(options::OPT_fmodules_decluse,
2555                    options::OPT_fno_modules_decluse, false))
2556     CmdArgs.push_back("-fmodules-decluse");
2557 
2558   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2559   // all #included headers are part of modules.
2560   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2561                    options::OPT_fno_modules_strict_decluse, false))
2562     CmdArgs.push_back("-fmodules-strict-decluse");
2563 
2564   // -fno-implicit-modules turns off implicitly compiling modules on demand.
2565   bool ImplicitModules = false;
2566   if (!Args.hasFlag(options::OPT_fimplicit_modules,
2567                     options::OPT_fno_implicit_modules, HaveClangModules)) {
2568     if (HaveModules)
2569       CmdArgs.push_back("-fno-implicit-modules");
2570   } else if (HaveModules) {
2571     ImplicitModules = true;
2572     // -fmodule-cache-path specifies where our implicitly-built module files
2573     // should be written.
2574     SmallString<128> Path;
2575     if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2576       Path = A->getValue();
2577 
2578     if (C.isForDiagnostics()) {
2579       // When generating crash reports, we want to emit the modules along with
2580       // the reproduction sources, so we ignore any provided module path.
2581       Path = Output.getFilename();
2582       llvm::sys::path::replace_extension(Path, ".cache");
2583       llvm::sys::path::append(Path, "modules");
2584     } else if (Path.empty()) {
2585       // No module path was provided: use the default.
2586       Driver::getDefaultModuleCachePath(Path);
2587     }
2588 
2589     const char Arg[] = "-fmodules-cache-path=";
2590     Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2591     CmdArgs.push_back(Args.MakeArgString(Path));
2592   }
2593 
2594   if (HaveModules) {
2595     // -fprebuilt-module-path specifies where to load the prebuilt module files.
2596     for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2597       CmdArgs.push_back(Args.MakeArgString(
2598           std::string("-fprebuilt-module-path=") + A->getValue()));
2599       A->claim();
2600     }
2601   }
2602 
2603   // -fmodule-name specifies the module that is currently being built (or
2604   // used for header checking by -fmodule-maps).
2605   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2606 
2607   // -fmodule-map-file can be used to specify files containing module
2608   // definitions.
2609   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2610 
2611   // -fbuiltin-module-map can be used to load the clang
2612   // builtin headers modulemap file.
2613   if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2614     SmallString<128> BuiltinModuleMap(D.ResourceDir);
2615     llvm::sys::path::append(BuiltinModuleMap, "include");
2616     llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2617     if (llvm::sys::fs::exists(BuiltinModuleMap))
2618       CmdArgs.push_back(
2619           Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2620   }
2621 
2622   // The -fmodule-file=<name>=<file> form specifies the mapping of module
2623   // names to precompiled module files (the module is loaded only if used).
2624   // The -fmodule-file=<file> form can be used to unconditionally load
2625   // precompiled module files (whether used or not).
2626   if (HaveModules)
2627     Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2628   else
2629     Args.ClaimAllArgs(options::OPT_fmodule_file);
2630 
2631   // When building modules and generating crashdumps, we need to dump a module
2632   // dependency VFS alongside the output.
2633   if (HaveClangModules && C.isForDiagnostics()) {
2634     SmallString<128> VFSDir(Output.getFilename());
2635     llvm::sys::path::replace_extension(VFSDir, ".cache");
2636     // Add the cache directory as a temp so the crash diagnostics pick it up.
2637     C.addTempFile(Args.MakeArgString(VFSDir));
2638 
2639     llvm::sys::path::append(VFSDir, "vfs");
2640     CmdArgs.push_back("-module-dependency-dir");
2641     CmdArgs.push_back(Args.MakeArgString(VFSDir));
2642   }
2643 
2644   if (HaveClangModules)
2645     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2646 
2647   // Pass through all -fmodules-ignore-macro arguments.
2648   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2649   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2650   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2651 
2652   Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2653 
2654   if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2655     if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2656       D.Diag(diag::err_drv_argument_not_allowed_with)
2657           << A->getAsString(Args) << "-fbuild-session-timestamp";
2658 
2659     llvm::sys::fs::file_status Status;
2660     if (llvm::sys::fs::status(A->getValue(), Status))
2661       D.Diag(diag::err_drv_no_such_file) << A->getValue();
2662     CmdArgs.push_back(
2663         Args.MakeArgString("-fbuild-session-timestamp=" +
2664                            Twine((uint64_t)Status.getLastModificationTime()
2665                                      .time_since_epoch()
2666                                      .count())));
2667   }
2668 
2669   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2670     if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2671                          options::OPT_fbuild_session_file))
2672       D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2673 
2674     Args.AddLastArg(CmdArgs,
2675                     options::OPT_fmodules_validate_once_per_build_session);
2676   }
2677 
2678   if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2679                    options::OPT_fno_modules_validate_system_headers,
2680                    ImplicitModules))
2681     CmdArgs.push_back("-fmodules-validate-system-headers");
2682 
2683   Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2684 }
2685 
2686 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2687                                    ArgStringList &CmdArgs) {
2688   // -fsigned-char is default.
2689   if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2690                                      options::OPT_fno_signed_char,
2691                                      options::OPT_funsigned_char,
2692                                      options::OPT_fno_unsigned_char)) {
2693     if (A->getOption().matches(options::OPT_funsigned_char) ||
2694         A->getOption().matches(options::OPT_fno_signed_char)) {
2695       CmdArgs.push_back("-fno-signed-char");
2696     }
2697   } else if (!isSignedCharDefault(T)) {
2698     CmdArgs.push_back("-fno-signed-char");
2699   }
2700 
2701   if (Args.hasFlag(options::OPT_fchar8__t, options::OPT_fno_char8__t, false))
2702     CmdArgs.push_back("-fchar8_t");
2703 
2704   if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2705                                      options::OPT_fno_short_wchar)) {
2706     if (A->getOption().matches(options::OPT_fshort_wchar)) {
2707       CmdArgs.push_back("-fwchar-type=short");
2708       CmdArgs.push_back("-fno-signed-wchar");
2709     } else {
2710       bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
2711       CmdArgs.push_back("-fwchar-type=int");
2712       if (IsARM && !(T.isOSWindows() || T.getOS() == llvm::Triple::NetBSD ||
2713                      T.getOS() == llvm::Triple::OpenBSD))
2714         CmdArgs.push_back("-fno-signed-wchar");
2715       else
2716         CmdArgs.push_back("-fsigned-wchar");
2717     }
2718   }
2719 }
2720 
2721 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2722                               const llvm::Triple &T, const ArgList &Args,
2723                               ObjCRuntime &Runtime, bool InferCovariantReturns,
2724                               const InputInfo &Input, ArgStringList &CmdArgs) {
2725   const llvm::Triple::ArchType Arch = TC.getArch();
2726 
2727   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2728   // is the default. Except for deployment target of 10.5, next runtime is
2729   // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2730   if (Runtime.isNonFragile()) {
2731     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2732                       options::OPT_fno_objc_legacy_dispatch,
2733                       Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2734       if (TC.UseObjCMixedDispatch())
2735         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2736       else
2737         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2738     }
2739   }
2740 
2741   // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2742   // to do Array/Dictionary subscripting by default.
2743   if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2744       !T.isMacOSXVersionLT(10, 7) &&
2745       Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2746     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2747 
2748   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2749   // NOTE: This logic is duplicated in ToolChains.cpp.
2750   if (isObjCAutoRefCount(Args)) {
2751     TC.CheckObjCARC();
2752 
2753     CmdArgs.push_back("-fobjc-arc");
2754 
2755     // FIXME: It seems like this entire block, and several around it should be
2756     // wrapped in isObjC, but for now we just use it here as this is where it
2757     // was being used previously.
2758     if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2759       if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2760         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2761       else
2762         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2763     }
2764 
2765     // Allow the user to enable full exceptions code emission.
2766     // We default off for Objective-C, on for Objective-C++.
2767     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2768                      options::OPT_fno_objc_arc_exceptions,
2769                      /*default=*/types::isCXX(Input.getType())))
2770       CmdArgs.push_back("-fobjc-arc-exceptions");
2771   }
2772 
2773   // Silence warning for full exception code emission options when explicitly
2774   // set to use no ARC.
2775   if (Args.hasArg(options::OPT_fno_objc_arc)) {
2776     Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2777     Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2778   }
2779 
2780   // -fobjc-infer-related-result-type is the default, except in the Objective-C
2781   // rewriter.
2782   if (InferCovariantReturns)
2783     CmdArgs.push_back("-fno-objc-infer-related-result-type");
2784 
2785   // Pass down -fobjc-weak or -fno-objc-weak if present.
2786   if (types::isObjC(Input.getType())) {
2787     auto WeakArg =
2788         Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2789     if (!WeakArg) {
2790       // nothing to do
2791     } else if (!Runtime.allowsWeak()) {
2792       if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2793         D.Diag(diag::err_objc_weak_unsupported);
2794     } else {
2795       WeakArg->render(Args, CmdArgs);
2796     }
2797   }
2798 }
2799 
2800 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2801                                      ArgStringList &CmdArgs) {
2802   bool CaretDefault = true;
2803   bool ColumnDefault = true;
2804 
2805   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2806                                      options::OPT__SLASH_diagnostics_column,
2807                                      options::OPT__SLASH_diagnostics_caret)) {
2808     switch (A->getOption().getID()) {
2809     case options::OPT__SLASH_diagnostics_caret:
2810       CaretDefault = true;
2811       ColumnDefault = true;
2812       break;
2813     case options::OPT__SLASH_diagnostics_column:
2814       CaretDefault = false;
2815       ColumnDefault = true;
2816       break;
2817     case options::OPT__SLASH_diagnostics_classic:
2818       CaretDefault = false;
2819       ColumnDefault = false;
2820       break;
2821     }
2822   }
2823 
2824   // -fcaret-diagnostics is default.
2825   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2826                     options::OPT_fno_caret_diagnostics, CaretDefault))
2827     CmdArgs.push_back("-fno-caret-diagnostics");
2828 
2829   // -fdiagnostics-fixit-info is default, only pass non-default.
2830   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2831                     options::OPT_fno_diagnostics_fixit_info))
2832     CmdArgs.push_back("-fno-diagnostics-fixit-info");
2833 
2834   // Enable -fdiagnostics-show-option by default.
2835   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2836                    options::OPT_fno_diagnostics_show_option))
2837     CmdArgs.push_back("-fdiagnostics-show-option");
2838 
2839   if (const Arg *A =
2840           Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2841     CmdArgs.push_back("-fdiagnostics-show-category");
2842     CmdArgs.push_back(A->getValue());
2843   }
2844 
2845   if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
2846                    options::OPT_fno_diagnostics_show_hotness, false))
2847     CmdArgs.push_back("-fdiagnostics-show-hotness");
2848 
2849   if (const Arg *A =
2850           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2851     std::string Opt =
2852         std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
2853     CmdArgs.push_back(Args.MakeArgString(Opt));
2854   }
2855 
2856   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2857     CmdArgs.push_back("-fdiagnostics-format");
2858     CmdArgs.push_back(A->getValue());
2859   }
2860 
2861   if (const Arg *A = Args.getLastArg(
2862           options::OPT_fdiagnostics_show_note_include_stack,
2863           options::OPT_fno_diagnostics_show_note_include_stack)) {
2864     const Option &O = A->getOption();
2865     if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
2866       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2867     else
2868       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2869   }
2870 
2871   // Color diagnostics are parsed by the driver directly from argv and later
2872   // re-parsed to construct this job; claim any possible color diagnostic here
2873   // to avoid warn_drv_unused_argument and diagnose bad
2874   // OPT_fdiagnostics_color_EQ values.
2875   for (const Arg *A : Args) {
2876     const Option &O = A->getOption();
2877     if (!O.matches(options::OPT_fcolor_diagnostics) &&
2878         !O.matches(options::OPT_fdiagnostics_color) &&
2879         !O.matches(options::OPT_fno_color_diagnostics) &&
2880         !O.matches(options::OPT_fno_diagnostics_color) &&
2881         !O.matches(options::OPT_fdiagnostics_color_EQ))
2882       continue;
2883 
2884     if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2885       StringRef Value(A->getValue());
2886       if (Value != "always" && Value != "never" && Value != "auto")
2887         D.Diag(diag::err_drv_clang_unsupported)
2888             << ("-fdiagnostics-color=" + Value).str();
2889     }
2890     A->claim();
2891   }
2892 
2893   if (D.getDiags().getDiagnosticOptions().ShowColors)
2894     CmdArgs.push_back("-fcolor-diagnostics");
2895 
2896   if (Args.hasArg(options::OPT_fansi_escape_codes))
2897     CmdArgs.push_back("-fansi-escape-codes");
2898 
2899   if (!Args.hasFlag(options::OPT_fshow_source_location,
2900                     options::OPT_fno_show_source_location))
2901     CmdArgs.push_back("-fno-show-source-location");
2902 
2903   if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
2904     CmdArgs.push_back("-fdiagnostics-absolute-paths");
2905 
2906   if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
2907                     ColumnDefault))
2908     CmdArgs.push_back("-fno-show-column");
2909 
2910   if (!Args.hasFlag(options::OPT_fspell_checking,
2911                     options::OPT_fno_spell_checking))
2912     CmdArgs.push_back("-fno-spell-checking");
2913 }
2914 
2915 static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
2916                                const llvm::Triple &T, const ArgList &Args,
2917                                bool EmitCodeView, bool IsWindowsMSVC,
2918                                ArgStringList &CmdArgs,
2919                                codegenoptions::DebugInfoKind &DebugInfoKind,
2920                                const Arg *&SplitDWARFArg) {
2921   if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
2922                    options::OPT_fno_debug_info_for_profiling, false) &&
2923       checkDebugInfoOption(
2924           Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
2925     CmdArgs.push_back("-fdebug-info-for-profiling");
2926 
2927   // The 'g' groups options involve a somewhat intricate sequence of decisions
2928   // about what to pass from the driver to the frontend, but by the time they
2929   // reach cc1 they've been factored into three well-defined orthogonal choices:
2930   //  * what level of debug info to generate
2931   //  * what dwarf version to write
2932   //  * what debugger tuning to use
2933   // This avoids having to monkey around further in cc1 other than to disable
2934   // codeview if not running in a Windows environment. Perhaps even that
2935   // decision should be made in the driver as well though.
2936   unsigned DWARFVersion = 0;
2937   llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
2938 
2939   bool SplitDWARFInlining =
2940       Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2941                    options::OPT_fno_split_dwarf_inlining, true);
2942 
2943   Args.ClaimAllArgs(options::OPT_g_Group);
2944 
2945   SplitDWARFArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2946 
2947   if (SplitDWARFArg && !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
2948     SplitDWARFArg = nullptr;
2949     SplitDWARFInlining = false;
2950   }
2951 
2952   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2953     if (checkDebugInfoOption(A, Args, D, TC)) {
2954       // If the last option explicitly specified a debug-info level, use it.
2955       if (A->getOption().matches(options::OPT_gN_Group)) {
2956         DebugInfoKind = DebugLevelToInfoKind(*A);
2957         // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2958         // But -gsplit-dwarf is not a g_group option, hence we have to check the
2959         // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
2960         // This gets a bit more complicated if you've disabled inline info in
2961         // the skeleton CUs (SplitDWARFInlining) - then there's value in
2962         // composing split-dwarf and line-tables-only, so let those compose
2963         // naturally in that case. And if you just turned off debug info,
2964         // (-gsplit-dwarf -g0) - do that.
2965         if (SplitDWARFArg) {
2966           if (A->getIndex() > SplitDWARFArg->getIndex()) {
2967             if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2968                 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
2969                 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2970                  SplitDWARFInlining))
2971               SplitDWARFArg = nullptr;
2972           } else if (SplitDWARFInlining)
2973             DebugInfoKind = codegenoptions::NoDebugInfo;
2974         }
2975       } else {
2976         // For any other 'g' option, use Limited.
2977         DebugInfoKind = codegenoptions::LimitedDebugInfo;
2978       }
2979     } else {
2980       DebugInfoKind = codegenoptions::LimitedDebugInfo;
2981     }
2982   }
2983 
2984   // If a debugger tuning argument appeared, remember it.
2985   if (const Arg *A =
2986           Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
2987     if (checkDebugInfoOption(A, Args, D, TC)) {
2988       if (A->getOption().matches(options::OPT_glldb))
2989         DebuggerTuning = llvm::DebuggerKind::LLDB;
2990       else if (A->getOption().matches(options::OPT_gsce))
2991         DebuggerTuning = llvm::DebuggerKind::SCE;
2992       else
2993         DebuggerTuning = llvm::DebuggerKind::GDB;
2994     }
2995   }
2996 
2997   // If a -gdwarf argument appeared, remember it.
2998   if (const Arg *A =
2999           Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3000                           options::OPT_gdwarf_4, options::OPT_gdwarf_5))
3001     if (checkDebugInfoOption(A, Args, D, TC))
3002       DWARFVersion = DwarfVersionNum(A->getSpelling());
3003 
3004   // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
3005   // argument parsing.
3006   if (EmitCodeView) {
3007     if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3008       EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
3009       if (EmitCodeView) {
3010         // DWARFVersion remains at 0 if no explicit choice was made.
3011         CmdArgs.push_back("-gcodeview");
3012       }
3013     }
3014   }
3015 
3016   if (!EmitCodeView && DWARFVersion == 0 &&
3017       DebugInfoKind != codegenoptions::NoDebugInfo)
3018     DWARFVersion = TC.GetDefaultDwarfVersion();
3019 
3020   // -gline-directives-only supported only for the DWARF debug info.
3021   if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3022     DebugInfoKind = codegenoptions::NoDebugInfo;
3023 
3024   // We ignore flag -gstrict-dwarf for now.
3025   // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3026   Args.ClaimAllArgs(options::OPT_g_flags_Group);
3027 
3028   // Column info is included by default for everything except SCE and
3029   // CodeView. Clang doesn't track end columns, just starting columns, which,
3030   // in theory, is fine for CodeView (and PDB).  In practice, however, the
3031   // Microsoft debuggers don't handle missing end columns well, so it's better
3032   // not to include any column info.
3033   if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3034     (void)checkDebugInfoOption(A, Args, D, TC);
3035   if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3036                    /*Default=*/!EmitCodeView &&
3037                        DebuggerTuning != llvm::DebuggerKind::SCE))
3038     CmdArgs.push_back("-dwarf-column-info");
3039 
3040   // FIXME: Move backend command line options to the module.
3041   // If -gline-tables-only or -gline-directives-only is the last option it wins.
3042   if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3043     if (checkDebugInfoOption(A, Args, D, TC)) {
3044       if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3045           DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
3046         DebugInfoKind = codegenoptions::LimitedDebugInfo;
3047         CmdArgs.push_back("-dwarf-ext-refs");
3048         CmdArgs.push_back("-fmodule-format=obj");
3049       }
3050     }
3051 
3052   // -gsplit-dwarf should turn on -g and enable the backend dwarf
3053   // splitting and extraction.
3054   // FIXME: Currently only works on Linux and Fuchsia.
3055   if (T.isOSLinux() || T.isOSFuchsia()) {
3056     if (!SplitDWARFInlining)
3057       CmdArgs.push_back("-fno-split-dwarf-inlining");
3058 
3059     if (SplitDWARFArg) {
3060       if (DebugInfoKind == codegenoptions::NoDebugInfo)
3061         DebugInfoKind = codegenoptions::LimitedDebugInfo;
3062       CmdArgs.push_back("-enable-split-dwarf");
3063     }
3064   }
3065 
3066   // After we've dealt with all combinations of things that could
3067   // make DebugInfoKind be other than None or DebugLineTablesOnly,
3068   // figure out if we need to "upgrade" it to standalone debug info.
3069   // We parse these two '-f' options whether or not they will be used,
3070   // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3071   bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
3072                                     options::OPT_fno_standalone_debug,
3073                                     TC.GetDefaultStandaloneDebug());
3074   if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3075     (void)checkDebugInfoOption(A, Args, D, TC);
3076   if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3077     DebugInfoKind = codegenoptions::FullDebugInfo;
3078 
3079   if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3080                    false)) {
3081     // Source embedding is a vendor extension to DWARF v5. By now we have
3082     // checked if a DWARF version was stated explicitly, and have otherwise
3083     // fallen back to the target default, so if this is still not at least 5
3084     // we emit an error.
3085     const Arg *A = Args.getLastArg(options::OPT_gembed_source);
3086     if (DWARFVersion < 5)
3087       D.Diag(diag::err_drv_argument_only_allowed_with)
3088           << A->getAsString(Args) << "-gdwarf-5";
3089     else if (checkDebugInfoOption(A, Args, D, TC))
3090       CmdArgs.push_back("-gembed-source");
3091   }
3092 
3093   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3094                           DebuggerTuning);
3095 
3096   // -fdebug-macro turns on macro debug info generation.
3097   if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3098                    false))
3099     if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3100                              D, TC))
3101       CmdArgs.push_back("-debug-info-macro");
3102 
3103   // -ggnu-pubnames turns on gnu style pubnames in the backend.
3104   const auto *PubnamesArg =
3105       Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3106                       options::OPT_gpubnames, options::OPT_gno_pubnames);
3107   if (SplitDWARFArg || DebuggerTuning == llvm::DebuggerKind::LLDB ||
3108       (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3109     if (!PubnamesArg ||
3110         (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3111          !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3112       CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3113                                            options::OPT_gpubnames)
3114                             ? "-gpubnames"
3115                             : "-ggnu-pubnames");
3116 
3117   // -gdwarf-aranges turns on the emission of the aranges section in the
3118   // backend.
3119   // Always enabled for SCE tuning.
3120   bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3121   if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3122     NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3123   if (NeedAranges) {
3124     CmdArgs.push_back("-mllvm");
3125     CmdArgs.push_back("-generate-arange-section");
3126   }
3127 
3128   if (Args.hasFlag(options::OPT_fdebug_types_section,
3129                    options::OPT_fno_debug_types_section, false)) {
3130     if (!T.isOSBinFormatELF()) {
3131       D.Diag(diag::err_drv_unsupported_opt_for_target)
3132           << Args.getLastArg(options::OPT_fdebug_types_section)
3133                  ->getAsString(Args)
3134           << T.getTriple();
3135     } else if (checkDebugInfoOption(
3136                    Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3137                    TC)) {
3138       CmdArgs.push_back("-mllvm");
3139       CmdArgs.push_back("-generate-type-units");
3140     }
3141   }
3142 
3143   // Decide how to render forward declarations of template instantiations.
3144   // SCE wants full descriptions, others just get them in the name.
3145   if (DebuggerTuning == llvm::DebuggerKind::SCE)
3146     CmdArgs.push_back("-debug-forward-template-params");
3147 
3148   // Do we need to explicitly import anonymous namespaces into the parent
3149   // scope?
3150   if (DebuggerTuning == llvm::DebuggerKind::SCE)
3151     CmdArgs.push_back("-dwarf-explicit-import");
3152 
3153   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
3154 }
3155 
3156 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3157                          const InputInfo &Output, const InputInfoList &Inputs,
3158                          const ArgList &Args, const char *LinkingOutput) const {
3159   const auto &TC = getToolChain();
3160   const llvm::Triple &RawTriple = TC.getTriple();
3161   const llvm::Triple &Triple = TC.getEffectiveTriple();
3162   const std::string &TripleStr = Triple.getTriple();
3163 
3164   bool KernelOrKext =
3165       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3166   const Driver &D = TC.getDriver();
3167   ArgStringList CmdArgs;
3168 
3169   // Check number of inputs for sanity. We need at least one input.
3170   assert(Inputs.size() >= 1 && "Must have at least one input.");
3171   // CUDA/HIP compilation may have multiple inputs (source file + results of
3172   // device-side compilations). OpenMP device jobs also take the host IR as a
3173   // second input. Module precompilation accepts a list of header files to
3174   // include as part of the module. All other jobs are expected to have exactly
3175   // one input.
3176   bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3177   bool IsHIP = JA.isOffloading(Action::OFK_HIP);
3178   bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
3179   bool IsModulePrecompile =
3180       isa<PrecompileJobAction>(JA) && JA.getType() == types::TY_ModuleFile;
3181   bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3182 
3183   // A header module compilation doesn't have a main input file, so invent a
3184   // fake one as a placeholder.
3185   // FIXME: Pick the language based on the header file language.
3186   const char *ModuleName = [&]{
3187     auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3188     return ModuleNameArg ? ModuleNameArg->getValue() : "";
3189   }();
3190   InputInfo HeaderModuleInput(types::TY_CXXModule, ModuleName, ModuleName);
3191 
3192   const InputInfo &Input =
3193       IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3194 
3195   InputInfoList ModuleHeaderInputs;
3196   const InputInfo *CudaDeviceInput = nullptr;
3197   const InputInfo *OpenMPDeviceInput = nullptr;
3198   for (const InputInfo &I : Inputs) {
3199     if (&I == &Input) {
3200       // This is the primary input.
3201     } else if (IsModulePrecompile &&
3202                types::getPrecompiledType(I.getType()) == types::TY_PCH) {
3203       types::ID Expected =
3204           types::lookupHeaderTypeForSourceType(Inputs[0].getType());
3205       if (I.getType() != Expected) {
3206         D.Diag(diag::err_drv_module_header_wrong_kind)
3207             << I.getFilename() << types::getTypeName(I.getType())
3208             << types::getTypeName(Expected);
3209       }
3210       ModuleHeaderInputs.push_back(I);
3211     } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3212       CudaDeviceInput = &I;
3213     } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3214       OpenMPDeviceInput = &I;
3215     } else {
3216       llvm_unreachable("unexpectedly given multiple inputs");
3217     }
3218   }
3219 
3220   const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
3221   bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3222   bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3223   bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
3224   bool IsIAMCU = RawTriple.isOSIAMCU();
3225 
3226   // Adjust IsWindowsXYZ for CUDA/HIP compilations.  Even when compiling in
3227   // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3228   // Windows), we need to pass Windows-specific flags to cc1.
3229   if (IsCuda || IsHIP) {
3230     IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3231     IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3232     IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3233   }
3234 
3235   // C++ is not supported for IAMCU.
3236   if (IsIAMCU && types::isCXX(Input.getType()))
3237     D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3238 
3239   // Invoke ourselves in -cc1 mode.
3240   //
3241   // FIXME: Implement custom jobs for internal actions.
3242   CmdArgs.push_back("-cc1");
3243 
3244   // Add the "effective" target triple.
3245   CmdArgs.push_back("-triple");
3246   CmdArgs.push_back(Args.MakeArgString(TripleStr));
3247 
3248   if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3249     DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3250     Args.ClaimAllArgs(options::OPT_MJ);
3251   }
3252 
3253   if (IsCuda || IsHIP) {
3254     // We have to pass the triple of the host if compiling for a CUDA/HIP device
3255     // and vice-versa.
3256     std::string NormalizedTriple;
3257     if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3258         JA.isDeviceOffloading(Action::OFK_HIP))
3259       NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3260                              ->getTriple()
3261                              .normalize();
3262     else
3263       NormalizedTriple =
3264           (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3265                   : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3266               ->getTriple()
3267               .normalize();
3268 
3269     CmdArgs.push_back("-aux-triple");
3270     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3271   }
3272 
3273   if (IsOpenMPDevice) {
3274     // We have to pass the triple of the host if compiling for an OpenMP device.
3275     std::string NormalizedTriple =
3276         C.getSingleOffloadToolChain<Action::OFK_Host>()
3277             ->getTriple()
3278             .normalize();
3279     CmdArgs.push_back("-aux-triple");
3280     CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3281   }
3282 
3283   if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3284                                Triple.getArch() == llvm::Triple::thumb)) {
3285     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3286     unsigned Version;
3287     Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3288     if (Version < 7)
3289       D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3290                                                 << TripleStr;
3291   }
3292 
3293   // Push all default warning arguments that are specific to
3294   // the given target.  These come before user provided warning options
3295   // are provided.
3296   TC.addClangWarningOptions(CmdArgs);
3297 
3298   // Select the appropriate action.
3299   RewriteKind rewriteKind = RK_None;
3300 
3301   if (isa<AnalyzeJobAction>(JA)) {
3302     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3303     CmdArgs.push_back("-analyze");
3304   } else if (isa<MigrateJobAction>(JA)) {
3305     CmdArgs.push_back("-migrate");
3306   } else if (isa<PreprocessJobAction>(JA)) {
3307     if (Output.getType() == types::TY_Dependencies)
3308       CmdArgs.push_back("-Eonly");
3309     else {
3310       CmdArgs.push_back("-E");
3311       if (Args.hasArg(options::OPT_rewrite_objc) &&
3312           !Args.hasArg(options::OPT_g_Group))
3313         CmdArgs.push_back("-P");
3314     }
3315   } else if (isa<AssembleJobAction>(JA)) {
3316     CmdArgs.push_back("-emit-obj");
3317 
3318     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3319 
3320     // Also ignore explicit -force_cpusubtype_ALL option.
3321     (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3322   } else if (isa<PrecompileJobAction>(JA)) {
3323     // Use PCH if the user requested it.
3324     bool UsePCH = D.CCCUsePCH;
3325 
3326     if (JA.getType() == types::TY_Nothing)
3327       CmdArgs.push_back("-fsyntax-only");
3328     else if (JA.getType() == types::TY_ModuleFile)
3329       CmdArgs.push_back(IsHeaderModulePrecompile
3330                             ? "-emit-header-module"
3331                             : "-emit-module-interface");
3332     else if (UsePCH)
3333       CmdArgs.push_back("-emit-pch");
3334     else
3335       CmdArgs.push_back("-emit-pth");
3336   } else if (isa<VerifyPCHJobAction>(JA)) {
3337     CmdArgs.push_back("-verify-pch");
3338   } else {
3339     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3340            "Invalid action for clang tool.");
3341     if (JA.getType() == types::TY_Nothing) {
3342       CmdArgs.push_back("-fsyntax-only");
3343     } else if (JA.getType() == types::TY_LLVM_IR ||
3344                JA.getType() == types::TY_LTO_IR) {
3345       CmdArgs.push_back("-emit-llvm");
3346     } else if (JA.getType() == types::TY_LLVM_BC ||
3347                JA.getType() == types::TY_LTO_BC) {
3348       CmdArgs.push_back("-emit-llvm-bc");
3349     } else if (JA.getType() == types::TY_PP_Asm) {
3350       CmdArgs.push_back("-S");
3351     } else if (JA.getType() == types::TY_AST) {
3352       CmdArgs.push_back("-emit-pch");
3353     } else if (JA.getType() == types::TY_ModuleFile) {
3354       CmdArgs.push_back("-module-file-info");
3355     } else if (JA.getType() == types::TY_RewrittenObjC) {
3356       CmdArgs.push_back("-rewrite-objc");
3357       rewriteKind = RK_NonFragile;
3358     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3359       CmdArgs.push_back("-rewrite-objc");
3360       rewriteKind = RK_Fragile;
3361     } else {
3362       assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3363     }
3364 
3365     // Preserve use-list order by default when emitting bitcode, so that
3366     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3367     // same result as running passes here.  For LTO, we don't need to preserve
3368     // the use-list order, since serialization to bitcode is part of the flow.
3369     if (JA.getType() == types::TY_LLVM_BC)
3370       CmdArgs.push_back("-emit-llvm-uselists");
3371 
3372     // Device-side jobs do not support LTO.
3373     bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3374                                    JA.isDeviceOffloading(Action::OFK_Host));
3375 
3376     if (D.isUsingLTO() && !isDeviceOffloadAction) {
3377       Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3378 
3379       // The Darwin and PS4 linkers currently use the legacy LTO API, which
3380       // does not support LTO unit features (CFI, whole program vtable opt)
3381       // under ThinLTO.
3382       if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
3383           D.getLTOMode() == LTOK_Full)
3384         CmdArgs.push_back("-flto-unit");
3385     }
3386   }
3387 
3388   if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3389     if (!types::isLLVMIR(Input.getType()))
3390       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3391                                                        << "-x ir";
3392     Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3393   }
3394 
3395   if (Args.getLastArg(options::OPT_save_temps_EQ))
3396     Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3397 
3398   // Embed-bitcode option.
3399   // Only white-listed flags below are allowed to be embedded.
3400   if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3401       (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3402     // Add flags implied by -fembed-bitcode.
3403     Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3404     // Disable all llvm IR level optimizations.
3405     CmdArgs.push_back("-disable-llvm-passes");
3406 
3407     // reject options that shouldn't be supported in bitcode
3408     // also reject kernel/kext
3409     static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3410         options::OPT_mkernel,
3411         options::OPT_fapple_kext,
3412         options::OPT_ffunction_sections,
3413         options::OPT_fno_function_sections,
3414         options::OPT_fdata_sections,
3415         options::OPT_fno_data_sections,
3416         options::OPT_funique_section_names,
3417         options::OPT_fno_unique_section_names,
3418         options::OPT_mrestrict_it,
3419         options::OPT_mno_restrict_it,
3420         options::OPT_mstackrealign,
3421         options::OPT_mno_stackrealign,
3422         options::OPT_mstack_alignment,
3423         options::OPT_mcmodel_EQ,
3424         options::OPT_mlong_calls,
3425         options::OPT_mno_long_calls,
3426         options::OPT_ggnu_pubnames,
3427         options::OPT_gdwarf_aranges,
3428         options::OPT_fdebug_types_section,
3429         options::OPT_fno_debug_types_section,
3430         options::OPT_fdwarf_directory_asm,
3431         options::OPT_fno_dwarf_directory_asm,
3432         options::OPT_mrelax_all,
3433         options::OPT_mno_relax_all,
3434         options::OPT_ftrap_function_EQ,
3435         options::OPT_ffixed_r9,
3436         options::OPT_mfix_cortex_a53_835769,
3437         options::OPT_mno_fix_cortex_a53_835769,
3438         options::OPT_ffixed_x18,
3439         options::OPT_mglobal_merge,
3440         options::OPT_mno_global_merge,
3441         options::OPT_mred_zone,
3442         options::OPT_mno_red_zone,
3443         options::OPT_Wa_COMMA,
3444         options::OPT_Xassembler,
3445         options::OPT_mllvm,
3446     };
3447     for (const auto &A : Args)
3448       if (std::find(std::begin(kBitcodeOptionBlacklist),
3449                     std::end(kBitcodeOptionBlacklist),
3450                     A->getOption().getID()) !=
3451           std::end(kBitcodeOptionBlacklist))
3452         D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3453 
3454     // Render the CodeGen options that need to be passed.
3455     if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3456                       options::OPT_fno_optimize_sibling_calls))
3457       CmdArgs.push_back("-mdisable-tail-calls");
3458 
3459     RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3460                                CmdArgs);
3461 
3462     // Render ABI arguments
3463     switch (TC.getArch()) {
3464     default: break;
3465     case llvm::Triple::arm:
3466     case llvm::Triple::armeb:
3467     case llvm::Triple::thumbeb:
3468       RenderARMABI(Triple, Args, CmdArgs);
3469       break;
3470     case llvm::Triple::aarch64:
3471     case llvm::Triple::aarch64_be:
3472       RenderAArch64ABI(Triple, Args, CmdArgs);
3473       break;
3474     }
3475 
3476     // Optimization level for CodeGen.
3477     if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3478       if (A->getOption().matches(options::OPT_O4)) {
3479         CmdArgs.push_back("-O3");
3480         D.Diag(diag::warn_O4_is_O3);
3481       } else {
3482         A->render(Args, CmdArgs);
3483       }
3484     }
3485 
3486     // Input/Output file.
3487     if (Output.getType() == types::TY_Dependencies) {
3488       // Handled with other dependency code.
3489     } else if (Output.isFilename()) {
3490       CmdArgs.push_back("-o");
3491       CmdArgs.push_back(Output.getFilename());
3492     } else {
3493       assert(Output.isNothing() && "Input output.");
3494     }
3495 
3496     for (const auto &II : Inputs) {
3497       addDashXForInput(Args, II, CmdArgs);
3498       if (II.isFilename())
3499         CmdArgs.push_back(II.getFilename());
3500       else
3501         II.getInputArg().renderAsInput(Args, CmdArgs);
3502     }
3503 
3504     C.addCommand(llvm::make_unique<Command>(JA, *this, D.getClangProgramPath(),
3505                                             CmdArgs, Inputs));
3506     return;
3507   }
3508 
3509   if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3510     CmdArgs.push_back("-fembed-bitcode=marker");
3511 
3512   // We normally speed up the clang process a bit by skipping destructors at
3513   // exit, but when we're generating diagnostics we can rely on some of the
3514   // cleanup.
3515   if (!C.isForDiagnostics())
3516     CmdArgs.push_back("-disable-free");
3517 
3518 #ifdef NDEBUG
3519   const bool IsAssertBuild = false;
3520 #else
3521   const bool IsAssertBuild = true;
3522 #endif
3523 
3524   // Disable the verification pass in -asserts builds.
3525   if (!IsAssertBuild)
3526     CmdArgs.push_back("-disable-llvm-verifier");
3527 
3528   // Discard value names in assert builds unless otherwise specified.
3529   if (Args.hasFlag(options::OPT_fdiscard_value_names,
3530                    options::OPT_fno_discard_value_names, !IsAssertBuild))
3531     CmdArgs.push_back("-discard-value-names");
3532 
3533   // Set the main file name, so that debug info works even with
3534   // -save-temps.
3535   CmdArgs.push_back("-main-file-name");
3536   CmdArgs.push_back(getBaseInputName(Args, Input));
3537 
3538   // Some flags which affect the language (via preprocessor
3539   // defines).
3540   if (Args.hasArg(options::OPT_static))
3541     CmdArgs.push_back("-static-define");
3542 
3543   if (Args.hasArg(options::OPT_municode))
3544     CmdArgs.push_back("-DUNICODE");
3545 
3546   if (isa<AnalyzeJobAction>(JA))
3547     RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
3548 
3549   CheckCodeGenerationOptions(D, Args);
3550 
3551   unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
3552   assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3553   if (FunctionAlignment) {
3554     CmdArgs.push_back("-function-alignment");
3555     CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3556   }
3557 
3558   llvm::Reloc::Model RelocationModel;
3559   unsigned PICLevel;
3560   bool IsPIE;
3561   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
3562 
3563   const char *RMName = RelocationModelName(RelocationModel);
3564 
3565   if ((RelocationModel == llvm::Reloc::ROPI ||
3566        RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3567       types::isCXX(Input.getType()) &&
3568       !Args.hasArg(options::OPT_fallow_unsupported))
3569     D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3570 
3571   if (RMName) {
3572     CmdArgs.push_back("-mrelocation-model");
3573     CmdArgs.push_back(RMName);
3574   }
3575   if (PICLevel > 0) {
3576     CmdArgs.push_back("-pic-level");
3577     CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3578     if (IsPIE)
3579       CmdArgs.push_back("-pic-is-pie");
3580   }
3581 
3582   if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3583     CmdArgs.push_back("-meabi");
3584     CmdArgs.push_back(A->getValue());
3585   }
3586 
3587   CmdArgs.push_back("-mthread-model");
3588   if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3589     if (!TC.isThreadModelSupported(A->getValue()))
3590       D.Diag(diag::err_drv_invalid_thread_model_for_target)
3591           << A->getValue() << A->getAsString(Args);
3592     CmdArgs.push_back(A->getValue());
3593   }
3594   else
3595     CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
3596 
3597   Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3598 
3599   if (Args.hasFlag(options::OPT_fmerge_all_constants,
3600                    options::OPT_fno_merge_all_constants, false))
3601     CmdArgs.push_back("-fmerge-all-constants");
3602 
3603   if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3604                    options::OPT_fdelete_null_pointer_checks, false))
3605     CmdArgs.push_back("-fno-delete-null-pointer-checks");
3606 
3607   // LLVM Code Generator Options.
3608 
3609   if (Args.hasArg(options::OPT_frewrite_map_file) ||
3610       Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3611     for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3612                                       options::OPT_frewrite_map_file_EQ)) {
3613       StringRef Map = A->getValue();
3614       if (!llvm::sys::fs::exists(Map)) {
3615         D.Diag(diag::err_drv_no_such_file) << Map;
3616       } else {
3617         CmdArgs.push_back("-frewrite-map-file");
3618         CmdArgs.push_back(A->getValue());
3619         A->claim();
3620       }
3621     }
3622   }
3623 
3624   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3625     StringRef v = A->getValue();
3626     CmdArgs.push_back("-mllvm");
3627     CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3628     A->claim();
3629   }
3630 
3631   if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3632                     true))
3633     CmdArgs.push_back("-fno-jump-tables");
3634 
3635   if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3636                    options::OPT_fno_profile_sample_accurate, false))
3637     CmdArgs.push_back("-fprofile-sample-accurate");
3638 
3639   if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3640                     options::OPT_fno_preserve_as_comments, true))
3641     CmdArgs.push_back("-fno-preserve-as-comments");
3642 
3643   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3644     CmdArgs.push_back("-mregparm");
3645     CmdArgs.push_back(A->getValue());
3646   }
3647 
3648   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3649                                options::OPT_freg_struct_return)) {
3650     if (TC.getArch() != llvm::Triple::x86) {
3651       D.Diag(diag::err_drv_unsupported_opt_for_target)
3652           << A->getSpelling() << RawTriple.str();
3653     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3654       CmdArgs.push_back("-fpcc-struct-return");
3655     } else {
3656       assert(A->getOption().matches(options::OPT_freg_struct_return));
3657       CmdArgs.push_back("-freg-struct-return");
3658     }
3659   }
3660 
3661   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3662     CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3663 
3664   if (shouldUseFramePointer(Args, RawTriple))
3665     CmdArgs.push_back("-mdisable-fp-elim");
3666   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3667                     options::OPT_fno_zero_initialized_in_bss))
3668     CmdArgs.push_back("-mno-zero-initialized-in-bss");
3669 
3670   bool OFastEnabled = isOptimizationLevelFast(Args);
3671   // If -Ofast is the optimization level, then -fstrict-aliasing should be
3672   // enabled.  This alias option is being used to simplify the hasFlag logic.
3673   OptSpecifier StrictAliasingAliasOption =
3674       OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3675   // We turn strict aliasing off by default if we're in CL mode, since MSVC
3676   // doesn't do any TBAA.
3677   bool TBAAOnByDefault = !D.IsCLMode();
3678   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3679                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3680     CmdArgs.push_back("-relaxed-aliasing");
3681   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3682                     options::OPT_fno_struct_path_tbaa))
3683     CmdArgs.push_back("-no-struct-path-tbaa");
3684   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3685                    false))
3686     CmdArgs.push_back("-fstrict-enums");
3687   if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3688                     true))
3689     CmdArgs.push_back("-fno-strict-return");
3690   if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3691                    options::OPT_fno_allow_editor_placeholders, false))
3692     CmdArgs.push_back("-fallow-editor-placeholders");
3693   if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3694                    options::OPT_fno_strict_vtable_pointers,
3695                    false))
3696     CmdArgs.push_back("-fstrict-vtable-pointers");
3697   if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3698                    options::OPT_fno_force_emit_vtables,
3699                    false))
3700     CmdArgs.push_back("-fforce-emit-vtables");
3701   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3702                     options::OPT_fno_optimize_sibling_calls))
3703     CmdArgs.push_back("-mdisable-tail-calls");
3704   if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
3705                    options::OPT_fescaping_block_tail_calls, false))
3706     CmdArgs.push_back("-fno-escaping-block-tail-calls");
3707 
3708   Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3709                   options::OPT_fno_fine_grained_bitfield_accesses);
3710 
3711   // Handle segmented stacks.
3712   if (Args.hasArg(options::OPT_fsplit_stack))
3713     CmdArgs.push_back("-split-stacks");
3714 
3715   RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
3716 
3717   // Decide whether to use verbose asm. Verbose assembly is the default on
3718   // toolchains which have the integrated assembler on by default.
3719   bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
3720   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3721                    IsIntegratedAssemblerDefault) ||
3722       Args.hasArg(options::OPT_dA))
3723     CmdArgs.push_back("-masm-verbose");
3724 
3725   if (!TC.useIntegratedAs())
3726     CmdArgs.push_back("-no-integrated-as");
3727 
3728   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3729     CmdArgs.push_back("-mdebug-pass");
3730     CmdArgs.push_back("Structure");
3731   }
3732   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3733     CmdArgs.push_back("-mdebug-pass");
3734     CmdArgs.push_back("Arguments");
3735   }
3736 
3737   // Enable -mconstructor-aliases except on darwin, where we have to work around
3738   // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3739   // aliases aren't supported.
3740   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
3741     CmdArgs.push_back("-mconstructor-aliases");
3742 
3743   // Darwin's kernel doesn't support guard variables; just die if we
3744   // try to use them.
3745   if (KernelOrKext && RawTriple.isOSDarwin())
3746     CmdArgs.push_back("-fforbid-guard-variables");
3747 
3748   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3749                    false)) {
3750     CmdArgs.push_back("-mms-bitfields");
3751   }
3752 
3753   if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3754                    options::OPT_mno_pie_copy_relocations,
3755                    false)) {
3756     CmdArgs.push_back("-mpie-copy-relocations");
3757   }
3758 
3759   if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3760     CmdArgs.push_back("-fno-plt");
3761   }
3762 
3763   // -fhosted is default.
3764   // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3765   // use Freestanding.
3766   bool Freestanding =
3767       Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3768       KernelOrKext;
3769   if (Freestanding)
3770     CmdArgs.push_back("-ffreestanding");
3771 
3772   // This is a coarse approximation of what llvm-gcc actually does, both
3773   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3774   // complicated ways.
3775   bool AsynchronousUnwindTables =
3776       Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3777                    options::OPT_fno_asynchronous_unwind_tables,
3778                    (TC.IsUnwindTablesDefault(Args) ||
3779                     TC.getSanitizerArgs().needsUnwindTables()) &&
3780                        !Freestanding);
3781   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3782                    AsynchronousUnwindTables))
3783     CmdArgs.push_back("-munwind-tables");
3784 
3785   TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
3786 
3787   // FIXME: Handle -mtune=.
3788   (void)Args.hasArg(options::OPT_mtune_EQ);
3789 
3790   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3791     CmdArgs.push_back("-mcode-model");
3792     CmdArgs.push_back(A->getValue());
3793   }
3794 
3795   // Add the target cpu
3796   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3797   if (!CPU.empty()) {
3798     CmdArgs.push_back("-target-cpu");
3799     CmdArgs.push_back(Args.MakeArgString(CPU));
3800   }
3801 
3802   RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
3803 
3804   // These two are potentially updated by AddClangCLArgs.
3805   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
3806   bool EmitCodeView = false;
3807 
3808   // Add clang-cl arguments.
3809   types::ID InputType = Input.getType();
3810   if (D.IsCLMode())
3811     AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
3812   else
3813     EmitCodeView = Args.hasArg(options::OPT_gcodeview);
3814 
3815   const Arg *SplitDWARFArg = nullptr;
3816   RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
3817                      CmdArgs, DebugInfoKind, SplitDWARFArg);
3818 
3819   // Add the split debug info name to the command lines here so we
3820   // can propagate it to the backend.
3821   bool SplitDWARF = SplitDWARFArg &&
3822                     (RawTriple.isOSLinux() || RawTriple.isOSFuchsia()) &&
3823                     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
3824                      isa<BackendJobAction>(JA));
3825   const char *SplitDWARFOut;
3826   if (SplitDWARF) {
3827     CmdArgs.push_back("-split-dwarf-file");
3828     SplitDWARFOut = SplitDebugName(Args, Input);
3829     CmdArgs.push_back(SplitDWARFOut);
3830   }
3831 
3832   // Pass the linker version in use.
3833   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3834     CmdArgs.push_back("-target-linker-version");
3835     CmdArgs.push_back(A->getValue());
3836   }
3837 
3838   if (!shouldUseLeafFramePointer(Args, RawTriple))
3839     CmdArgs.push_back("-momit-leaf-frame-pointer");
3840 
3841   // Explicitly error on some things we know we don't support and can't just
3842   // ignore.
3843   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3844     Arg *Unsupported;
3845     if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
3846         TC.getArch() == llvm::Triple::x86) {
3847       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3848           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3849         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3850             << Unsupported->getOption().getName();
3851     }
3852     // The faltivec option has been superseded by the maltivec option.
3853     if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
3854       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3855           << Unsupported->getOption().getName()
3856           << "please use -maltivec and include altivec.h explicitly";
3857     if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
3858       D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3859           << Unsupported->getOption().getName() << "please use -mno-altivec";
3860   }
3861 
3862   Args.AddAllArgs(CmdArgs, options::OPT_v);
3863   Args.AddLastArg(CmdArgs, options::OPT_H);
3864   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3865     CmdArgs.push_back("-header-include-file");
3866     CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3867                                                : "-");
3868   }
3869   Args.AddLastArg(CmdArgs, options::OPT_P);
3870   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3871 
3872   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3873     CmdArgs.push_back("-diagnostic-log-file");
3874     CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3875                                                  : "-");
3876   }
3877 
3878   bool UseSeparateSections = isUseSeparateSections(Triple);
3879 
3880   if (Args.hasFlag(options::OPT_ffunction_sections,
3881                    options::OPT_fno_function_sections, UseSeparateSections)) {
3882     CmdArgs.push_back("-ffunction-sections");
3883   }
3884 
3885   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3886                    UseSeparateSections)) {
3887     CmdArgs.push_back("-fdata-sections");
3888   }
3889 
3890   if (!Args.hasFlag(options::OPT_funique_section_names,
3891                     options::OPT_fno_unique_section_names, true))
3892     CmdArgs.push_back("-fno-unique-section-names");
3893 
3894   if (auto *A = Args.getLastArg(
3895       options::OPT_finstrument_functions,
3896       options::OPT_finstrument_functions_after_inlining,
3897       options::OPT_finstrument_function_entry_bare))
3898     A->render(Args, CmdArgs);
3899 
3900   // NVPTX doesn't support PGO or coverage. There's no runtime support for
3901   // sampling, overhead of call arc collection is way too high and there's no
3902   // way to collect the output.
3903   if (!Triple.isNVPTX())
3904     addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
3905 
3906   if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
3907     ABICompatArg->render(Args, CmdArgs);
3908 
3909   // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
3910   if (RawTriple.isPS4CPU()) {
3911     PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
3912     PS4cpu::addSanitizerArgs(TC, CmdArgs);
3913   }
3914 
3915   // Pass options for controlling the default header search paths.
3916   if (Args.hasArg(options::OPT_nostdinc)) {
3917     CmdArgs.push_back("-nostdsysteminc");
3918     CmdArgs.push_back("-nobuiltininc");
3919   } else {
3920     if (Args.hasArg(options::OPT_nostdlibinc))
3921       CmdArgs.push_back("-nostdsysteminc");
3922     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3923     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3924   }
3925 
3926   // Pass the path to compiler resource files.
3927   CmdArgs.push_back("-resource-dir");
3928   CmdArgs.push_back(D.ResourceDir.c_str());
3929 
3930   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3931 
3932   RenderARCMigrateToolOptions(D, Args, CmdArgs);
3933 
3934   // Add preprocessing options like -I, -D, etc. if we are using the
3935   // preprocessor.
3936   //
3937   // FIXME: Support -fpreprocessed
3938   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3939     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3940 
3941   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3942   // that "The compiler can only warn and ignore the option if not recognized".
3943   // When building with ccache, it will pass -D options to clang even on
3944   // preprocessed inputs and configure concludes that -fPIC is not supported.
3945   Args.ClaimAllArgs(options::OPT_D);
3946 
3947   // Manually translate -O4 to -O3; let clang reject others.
3948   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3949     if (A->getOption().matches(options::OPT_O4)) {
3950       CmdArgs.push_back("-O3");
3951       D.Diag(diag::warn_O4_is_O3);
3952     } else {
3953       A->render(Args, CmdArgs);
3954     }
3955   }
3956 
3957   // Warn about ignored options to clang.
3958   for (const Arg *A :
3959        Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3960     D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3961     A->claim();
3962   }
3963 
3964   for (const Arg *A :
3965        Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
3966     D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
3967     A->claim();
3968   }
3969 
3970   claimNoWarnArgs(Args);
3971 
3972   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3973 
3974   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3975   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3976     CmdArgs.push_back("-pedantic");
3977   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3978   Args.AddLastArg(CmdArgs, options::OPT_w);
3979 
3980   // Fixed point flags
3981   if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
3982                    /*Default=*/false))
3983     Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
3984 
3985   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3986   // (-ansi is equivalent to -std=c89 or -std=c++98).
3987   //
3988   // If a std is supplied, only add -trigraphs if it follows the
3989   // option.
3990   bool ImplyVCPPCXXVer = false;
3991   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3992     if (Std->getOption().matches(options::OPT_ansi))
3993       if (types::isCXX(InputType))
3994         CmdArgs.push_back("-std=c++98");
3995       else
3996         CmdArgs.push_back("-std=c89");
3997     else
3998       Std->render(Args, CmdArgs);
3999 
4000     // If -f(no-)trigraphs appears after the language standard flag, honor it.
4001     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4002                                  options::OPT_ftrigraphs,
4003                                  options::OPT_fno_trigraphs))
4004       if (A != Std)
4005         A->render(Args, CmdArgs);
4006   } else {
4007     // Honor -std-default.
4008     //
4009     // FIXME: Clang doesn't correctly handle -std= when the input language
4010     // doesn't match. For the time being just ignore this for C++ inputs;
4011     // eventually we want to do all the standard defaulting here instead of
4012     // splitting it between the driver and clang -cc1.
4013     if (!types::isCXX(InputType))
4014       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4015                                 /*Joined=*/true);
4016     else if (IsWindowsMSVC)
4017       ImplyVCPPCXXVer = true;
4018 
4019     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4020                     options::OPT_fno_trigraphs);
4021   }
4022 
4023   // GCC's behavior for -Wwrite-strings is a bit strange:
4024   //  * In C, this "warning flag" changes the types of string literals from
4025   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4026   //    for the discarded qualifier.
4027   //  * In C++, this is just a normal warning flag.
4028   //
4029   // Implementing this warning correctly in C is hard, so we follow GCC's
4030   // behavior for now. FIXME: Directly diagnose uses of a string literal as
4031   // a non-const char* in C, rather than using this crude hack.
4032   if (!types::isCXX(InputType)) {
4033     // FIXME: This should behave just like a warning flag, and thus should also
4034     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4035     Arg *WriteStrings =
4036         Args.getLastArg(options::OPT_Wwrite_strings,
4037                         options::OPT_Wno_write_strings, options::OPT_w);
4038     if (WriteStrings &&
4039         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4040       CmdArgs.push_back("-fconst-strings");
4041   }
4042 
4043   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4044   // during C++ compilation, which it is by default. GCC keeps this define even
4045   // in the presence of '-w', match this behavior bug-for-bug.
4046   if (types::isCXX(InputType) &&
4047       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4048                    true)) {
4049     CmdArgs.push_back("-fdeprecated-macro");
4050   }
4051 
4052   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4053   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4054     if (Asm->getOption().matches(options::OPT_fasm))
4055       CmdArgs.push_back("-fgnu-keywords");
4056     else
4057       CmdArgs.push_back("-fno-gnu-keywords");
4058   }
4059 
4060   if (ShouldDisableDwarfDirectory(Args, TC))
4061     CmdArgs.push_back("-fno-dwarf-directory-asm");
4062 
4063   if (ShouldDisableAutolink(Args, TC))
4064     CmdArgs.push_back("-fno-autolink");
4065 
4066   // Add in -fdebug-compilation-dir if necessary.
4067   addDebugCompDirArg(Args, CmdArgs);
4068 
4069   addDebugPrefixMapArg(D, Args, CmdArgs);
4070 
4071   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4072                                options::OPT_ftemplate_depth_EQ)) {
4073     CmdArgs.push_back("-ftemplate-depth");
4074     CmdArgs.push_back(A->getValue());
4075   }
4076 
4077   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4078     CmdArgs.push_back("-foperator-arrow-depth");
4079     CmdArgs.push_back(A->getValue());
4080   }
4081 
4082   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4083     CmdArgs.push_back("-fconstexpr-depth");
4084     CmdArgs.push_back(A->getValue());
4085   }
4086 
4087   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4088     CmdArgs.push_back("-fconstexpr-steps");
4089     CmdArgs.push_back(A->getValue());
4090   }
4091 
4092   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4093     CmdArgs.push_back("-fbracket-depth");
4094     CmdArgs.push_back(A->getValue());
4095   }
4096 
4097   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4098                                options::OPT_Wlarge_by_value_copy_def)) {
4099     if (A->getNumValues()) {
4100       StringRef bytes = A->getValue();
4101       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4102     } else
4103       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4104   }
4105 
4106   if (Args.hasArg(options::OPT_relocatable_pch))
4107     CmdArgs.push_back("-relocatable-pch");
4108 
4109   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4110     CmdArgs.push_back("-fconstant-string-class");
4111     CmdArgs.push_back(A->getValue());
4112   }
4113 
4114   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4115     CmdArgs.push_back("-ftabstop");
4116     CmdArgs.push_back(A->getValue());
4117   }
4118 
4119   if (Args.hasFlag(options::OPT_fstack_size_section,
4120                    options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4121     CmdArgs.push_back("-fstack-size-section");
4122 
4123   CmdArgs.push_back("-ferror-limit");
4124   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4125     CmdArgs.push_back(A->getValue());
4126   else
4127     CmdArgs.push_back("19");
4128 
4129   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4130     CmdArgs.push_back("-fmacro-backtrace-limit");
4131     CmdArgs.push_back(A->getValue());
4132   }
4133 
4134   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4135     CmdArgs.push_back("-ftemplate-backtrace-limit");
4136     CmdArgs.push_back(A->getValue());
4137   }
4138 
4139   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4140     CmdArgs.push_back("-fconstexpr-backtrace-limit");
4141     CmdArgs.push_back(A->getValue());
4142   }
4143 
4144   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4145     CmdArgs.push_back("-fspell-checking-limit");
4146     CmdArgs.push_back(A->getValue());
4147   }
4148 
4149   // Pass -fmessage-length=.
4150   CmdArgs.push_back("-fmessage-length");
4151   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4152     CmdArgs.push_back(A->getValue());
4153   } else {
4154     // If -fmessage-length=N was not specified, determine whether this is a
4155     // terminal and, if so, implicitly define -fmessage-length appropriately.
4156     unsigned N = llvm::sys::Process::StandardErrColumns();
4157     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4158   }
4159 
4160   // -fvisibility= and -fvisibility-ms-compat are of a piece.
4161   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4162                                      options::OPT_fvisibility_ms_compat)) {
4163     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4164       CmdArgs.push_back("-fvisibility");
4165       CmdArgs.push_back(A->getValue());
4166     } else {
4167       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4168       CmdArgs.push_back("-fvisibility");
4169       CmdArgs.push_back("hidden");
4170       CmdArgs.push_back("-ftype-visibility");
4171       CmdArgs.push_back("default");
4172     }
4173   }
4174 
4175   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4176 
4177   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4178 
4179   // Forward -f (flag) options which we can pass directly.
4180   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4181   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4182   Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
4183   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4184   Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4185                   options::OPT_fno_emulated_tls);
4186   Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
4187 
4188   // AltiVec-like language extensions aren't relevant for assembling.
4189   if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
4190     Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4191 
4192   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4193   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4194 
4195   // Forward flags for OpenMP. We don't do this if the current action is an
4196   // device offloading action other than OpenMP.
4197   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4198                    options::OPT_fno_openmp, false) &&
4199       (JA.isDeviceOffloading(Action::OFK_None) ||
4200        JA.isDeviceOffloading(Action::OFK_OpenMP))) {
4201     switch (D.getOpenMPRuntime(Args)) {
4202     case Driver::OMPRT_OMP:
4203     case Driver::OMPRT_IOMP5:
4204       // Clang can generate useful OpenMP code for these two runtime libraries.
4205       CmdArgs.push_back("-fopenmp");
4206 
4207       // If no option regarding the use of TLS in OpenMP codegeneration is
4208       // given, decide a default based on the target. Otherwise rely on the
4209       // options and pass the right information to the frontend.
4210       if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4211                         options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4212         CmdArgs.push_back("-fnoopenmp-use-tls");
4213       Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4214                       options::OPT_fno_openmp_simd);
4215       Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4216 
4217       // When in OpenMP offloading mode with NVPTX target, forward
4218       // cuda-mode flag
4219       if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4220                        options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4221         CmdArgs.push_back("-fopenmp-cuda-mode");
4222 
4223       // When in OpenMP offloading mode with NVPTX target, check if full runtime
4224       // is required.
4225       if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4226                        options::OPT_fno_openmp_cuda_force_full_runtime,
4227                        /*Default=*/false))
4228         CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
4229       break;
4230     default:
4231       // By default, if Clang doesn't know how to generate useful OpenMP code
4232       // for a specific runtime library, we just don't pass the '-fopenmp' flag
4233       // down to the actual compilation.
4234       // FIXME: It would be better to have a mode which *only* omits IR
4235       // generation based on the OpenMP support so that we get consistent
4236       // semantic analysis, etc.
4237       break;
4238     }
4239   } else {
4240     Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4241                     options::OPT_fno_openmp_simd);
4242     Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4243   }
4244 
4245   const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4246   Sanitize.addArgs(TC, Args, CmdArgs, InputType);
4247 
4248   const XRayArgs &XRay = TC.getXRayArgs();
4249   XRay.addArgs(TC, Args, CmdArgs, InputType);
4250 
4251   if (TC.SupportsProfiling())
4252     Args.AddLastArg(CmdArgs, options::OPT_pg);
4253 
4254   if (TC.SupportsProfiling())
4255     Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4256 
4257   // -flax-vector-conversions is default.
4258   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4259                     options::OPT_fno_lax_vector_conversions))
4260     CmdArgs.push_back("-fno-lax-vector-conversions");
4261 
4262   if (Args.getLastArg(options::OPT_fapple_kext) ||
4263       (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4264     CmdArgs.push_back("-fapple-kext");
4265 
4266   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4267   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4268   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4269   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4270   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4271 
4272   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4273     CmdArgs.push_back("-ftrapv-handler");
4274     CmdArgs.push_back(A->getValue());
4275   }
4276 
4277   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4278 
4279   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4280   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4281   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4282     if (A->getOption().matches(options::OPT_fwrapv))
4283       CmdArgs.push_back("-fwrapv");
4284   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4285                                       options::OPT_fno_strict_overflow)) {
4286     if (A->getOption().matches(options::OPT_fno_strict_overflow))
4287       CmdArgs.push_back("-fwrapv");
4288   }
4289 
4290   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4291                                options::OPT_fno_reroll_loops))
4292     if (A->getOption().matches(options::OPT_freroll_loops))
4293       CmdArgs.push_back("-freroll-loops");
4294 
4295   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4296   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4297                   options::OPT_fno_unroll_loops);
4298 
4299   Args.AddLastArg(CmdArgs, options::OPT_pthread);
4300 
4301   Args.AddLastArg(CmdArgs, options::OPT_mspeculative_load_hardening,
4302                   options::OPT_mno_speculative_load_hardening);
4303 
4304   RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
4305 
4306   // Translate -mstackrealign
4307   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4308                    false))
4309     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4310 
4311   if (Args.hasArg(options::OPT_mstack_alignment)) {
4312     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4313     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4314   }
4315 
4316   if (Args.hasArg(options::OPT_mstack_probe_size)) {
4317     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4318 
4319     if (!Size.empty())
4320       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4321     else
4322       CmdArgs.push_back("-mstack-probe-size=0");
4323   }
4324 
4325   if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4326                     options::OPT_mno_stack_arg_probe, true))
4327     CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4328 
4329   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4330                                options::OPT_mno_restrict_it)) {
4331     if (A->getOption().matches(options::OPT_mrestrict_it)) {
4332       CmdArgs.push_back("-mllvm");
4333       CmdArgs.push_back("-arm-restrict-it");
4334     } else {
4335       CmdArgs.push_back("-mllvm");
4336       CmdArgs.push_back("-arm-no-restrict-it");
4337     }
4338   } else if (Triple.isOSWindows() &&
4339              (Triple.getArch() == llvm::Triple::arm ||
4340               Triple.getArch() == llvm::Triple::thumb)) {
4341     // Windows on ARM expects restricted IT blocks
4342     CmdArgs.push_back("-mllvm");
4343     CmdArgs.push_back("-arm-restrict-it");
4344   }
4345 
4346   // Forward -cl options to -cc1
4347   RenderOpenCLOptions(Args, CmdArgs);
4348 
4349   if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4350     CmdArgs.push_back(
4351         Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4352   }
4353 
4354   // Forward -f options with positive and negative forms; we translate
4355   // these by hand.
4356   if (Arg *A = getLastProfileSampleUseArg(Args)) {
4357     StringRef fname = A->getValue();
4358     if (!llvm::sys::fs::exists(fname))
4359       D.Diag(diag::err_drv_no_such_file) << fname;
4360     else
4361       A->render(Args, CmdArgs);
4362   }
4363   Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
4364 
4365   RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
4366 
4367   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4368                     options::OPT_fno_assume_sane_operator_new))
4369     CmdArgs.push_back("-fno-assume-sane-operator-new");
4370 
4371   // -fblocks=0 is default.
4372   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4373                    TC.IsBlocksDefault()) ||
4374       (Args.hasArg(options::OPT_fgnu_runtime) &&
4375        Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4376        !Args.hasArg(options::OPT_fno_blocks))) {
4377     CmdArgs.push_back("-fblocks");
4378 
4379     if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
4380       CmdArgs.push_back("-fblocks-runtime-optional");
4381   }
4382 
4383   // -fencode-extended-block-signature=1 is default.
4384   if (TC.IsEncodeExtendedBlockSignatureDefault())
4385     CmdArgs.push_back("-fencode-extended-block-signature");
4386 
4387   if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4388                    false) &&
4389       types::isCXX(InputType)) {
4390     CmdArgs.push_back("-fcoroutines-ts");
4391   }
4392 
4393   Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4394                   options::OPT_fno_double_square_bracket_attributes);
4395 
4396   bool HaveModules = false;
4397   RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4398 
4399   // -faccess-control is default.
4400   if (Args.hasFlag(options::OPT_fno_access_control,
4401                    options::OPT_faccess_control, false))
4402     CmdArgs.push_back("-fno-access-control");
4403 
4404   // -felide-constructors is the default.
4405   if (Args.hasFlag(options::OPT_fno_elide_constructors,
4406                    options::OPT_felide_constructors, false))
4407     CmdArgs.push_back("-fno-elide-constructors");
4408 
4409   ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
4410 
4411   if (KernelOrKext || (types::isCXX(InputType) &&
4412                        (RTTIMode == ToolChain::RM_Disabled)))
4413     CmdArgs.push_back("-fno-rtti");
4414 
4415   // -fshort-enums=0 is default for all architectures except Hexagon.
4416   if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4417                    TC.getArch() == llvm::Triple::hexagon))
4418     CmdArgs.push_back("-fshort-enums");
4419 
4420   RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
4421 
4422   // -fuse-cxa-atexit is default.
4423   if (!Args.hasFlag(
4424           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4425           !RawTriple.isOSWindows() &&
4426               RawTriple.getOS() != llvm::Triple::Solaris &&
4427               TC.getArch() != llvm::Triple::xcore &&
4428               ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4429                RawTriple.hasEnvironment())) ||
4430       KernelOrKext)
4431     CmdArgs.push_back("-fno-use-cxa-atexit");
4432 
4433   if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4434                    options::OPT_fno_register_global_dtors_with_atexit,
4435                    RawTriple.isOSDarwin() && !KernelOrKext))
4436     CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4437 
4438   // -fms-extensions=0 is default.
4439   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4440                    IsWindowsMSVC))
4441     CmdArgs.push_back("-fms-extensions");
4442 
4443   // -fno-use-line-directives is default.
4444   if (Args.hasFlag(options::OPT_fuse_line_directives,
4445                    options::OPT_fno_use_line_directives, false))
4446     CmdArgs.push_back("-fuse-line-directives");
4447 
4448   // -fms-compatibility=0 is default.
4449   if (Args.hasFlag(options::OPT_fms_compatibility,
4450                    options::OPT_fno_ms_compatibility,
4451                    (IsWindowsMSVC &&
4452                     Args.hasFlag(options::OPT_fms_extensions,
4453                                  options::OPT_fno_ms_extensions, true))))
4454     CmdArgs.push_back("-fms-compatibility");
4455 
4456   VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
4457   if (!MSVT.empty())
4458     CmdArgs.push_back(
4459         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4460 
4461   bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4462   if (ImplyVCPPCXXVer) {
4463     StringRef LanguageStandard;
4464     if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4465       LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4466                              .Case("c++14", "-std=c++14")
4467                              .Case("c++17", "-std=c++17")
4468                              .Case("c++latest", "-std=c++2a")
4469                              .Default("");
4470       if (LanguageStandard.empty())
4471         D.Diag(clang::diag::warn_drv_unused_argument)
4472             << StdArg->getAsString(Args);
4473     }
4474 
4475     if (LanguageStandard.empty()) {
4476       if (IsMSVC2015Compatible)
4477         LanguageStandard = "-std=c++14";
4478       else
4479         LanguageStandard = "-std=c++11";
4480     }
4481 
4482     CmdArgs.push_back(LanguageStandard.data());
4483   }
4484 
4485   // -fno-borland-extensions is default.
4486   if (Args.hasFlag(options::OPT_fborland_extensions,
4487                    options::OPT_fno_borland_extensions, false))
4488     CmdArgs.push_back("-fborland-extensions");
4489 
4490   // -fno-declspec is default, except for PS4.
4491   if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
4492                    RawTriple.isPS4()))
4493     CmdArgs.push_back("-fdeclspec");
4494   else if (Args.hasArg(options::OPT_fno_declspec))
4495     CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4496 
4497   // -fthreadsafe-static is default, except for MSVC compatibility versions less
4498   // than 19.
4499   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4500                     options::OPT_fno_threadsafe_statics,
4501                     !IsWindowsMSVC || IsMSVC2015Compatible))
4502     CmdArgs.push_back("-fno-threadsafe-statics");
4503 
4504   // -fno-delayed-template-parsing is default, except when targeting MSVC.
4505   // Many old Windows SDK versions require this to parse.
4506   // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4507   // compiler. We should be able to disable this by default at some point.
4508   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4509                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4510     CmdArgs.push_back("-fdelayed-template-parsing");
4511 
4512   // -fgnu-keywords default varies depending on language; only pass if
4513   // specified.
4514   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4515                                options::OPT_fno_gnu_keywords))
4516     A->render(Args, CmdArgs);
4517 
4518   if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4519                    false))
4520     CmdArgs.push_back("-fgnu89-inline");
4521 
4522   if (Args.hasArg(options::OPT_fno_inline))
4523     CmdArgs.push_back("-fno-inline");
4524 
4525   if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4526                                        options::OPT_finline_hint_functions,
4527                                        options::OPT_fno_inline_functions))
4528     InlineArg->render(Args, CmdArgs);
4529 
4530   Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4531                   options::OPT_fno_experimental_new_pass_manager);
4532 
4533   ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4534   RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4535                     Input, CmdArgs);
4536 
4537   if (Args.hasFlag(options::OPT_fapplication_extension,
4538                    options::OPT_fno_application_extension, false))
4539     CmdArgs.push_back("-fapplication-extension");
4540 
4541   // Handle GCC-style exception args.
4542   if (!C.getDriver().IsCLMode())
4543     addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
4544 
4545   // Handle exception personalities
4546   Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4547                            options::OPT_fseh_exceptions,
4548                            options::OPT_fdwarf_exceptions);
4549   if (A) {
4550     const Option &Opt = A->getOption();
4551     if (Opt.matches(options::OPT_fsjlj_exceptions))
4552       CmdArgs.push_back("-fsjlj-exceptions");
4553     if (Opt.matches(options::OPT_fseh_exceptions))
4554       CmdArgs.push_back("-fseh-exceptions");
4555     if (Opt.matches(options::OPT_fdwarf_exceptions))
4556       CmdArgs.push_back("-fdwarf-exceptions");
4557   } else {
4558     switch (TC.GetExceptionModel(Args)) {
4559     default:
4560       break;
4561     case llvm::ExceptionHandling::DwarfCFI:
4562       CmdArgs.push_back("-fdwarf-exceptions");
4563       break;
4564     case llvm::ExceptionHandling::SjLj:
4565       CmdArgs.push_back("-fsjlj-exceptions");
4566       break;
4567     case llvm::ExceptionHandling::WinEH:
4568       CmdArgs.push_back("-fseh-exceptions");
4569       break;
4570     }
4571   }
4572 
4573   // C++ "sane" operator new.
4574   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4575                     options::OPT_fno_assume_sane_operator_new))
4576     CmdArgs.push_back("-fno-assume-sane-operator-new");
4577 
4578   // -frelaxed-template-template-args is off by default, as it is a severe
4579   // breaking change until a corresponding change to template partial ordering
4580   // is provided.
4581   if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4582                    options::OPT_fno_relaxed_template_template_args, false))
4583     CmdArgs.push_back("-frelaxed-template-template-args");
4584 
4585   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4586   // most platforms.
4587   if (Args.hasFlag(options::OPT_fsized_deallocation,
4588                    options::OPT_fno_sized_deallocation, false))
4589     CmdArgs.push_back("-fsized-deallocation");
4590 
4591   // -faligned-allocation is on by default in C++17 onwards and otherwise off
4592   // by default.
4593   if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4594                                options::OPT_fno_aligned_allocation,
4595                                options::OPT_faligned_new_EQ)) {
4596     if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4597       CmdArgs.push_back("-fno-aligned-allocation");
4598     else
4599       CmdArgs.push_back("-faligned-allocation");
4600   }
4601 
4602   // The default new alignment can be specified using a dedicated option or via
4603   // a GCC-compatible option that also turns on aligned allocation.
4604   if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4605                                options::OPT_faligned_new_EQ))
4606     CmdArgs.push_back(
4607         Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4608 
4609   // -fconstant-cfstrings is default, and may be subject to argument translation
4610   // on Darwin.
4611   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4612                     options::OPT_fno_constant_cfstrings) ||
4613       !Args.hasFlag(options::OPT_mconstant_cfstrings,
4614                     options::OPT_mno_constant_cfstrings))
4615     CmdArgs.push_back("-fno-constant-cfstrings");
4616 
4617   // -fno-pascal-strings is default, only pass non-default.
4618   if (Args.hasFlag(options::OPT_fpascal_strings,
4619                    options::OPT_fno_pascal_strings, false))
4620     CmdArgs.push_back("-fpascal-strings");
4621 
4622   // Honor -fpack-struct= and -fpack-struct, if given. Note that
4623   // -fno-pack-struct doesn't apply to -fpack-struct=.
4624   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4625     std::string PackStructStr = "-fpack-struct=";
4626     PackStructStr += A->getValue();
4627     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4628   } else if (Args.hasFlag(options::OPT_fpack_struct,
4629                           options::OPT_fno_pack_struct, false)) {
4630     CmdArgs.push_back("-fpack-struct=1");
4631   }
4632 
4633   // Handle -fmax-type-align=N and -fno-type-align
4634   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4635   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4636     if (!SkipMaxTypeAlign) {
4637       std::string MaxTypeAlignStr = "-fmax-type-align=";
4638       MaxTypeAlignStr += A->getValue();
4639       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4640     }
4641   } else if (RawTriple.isOSDarwin()) {
4642     if (!SkipMaxTypeAlign) {
4643       std::string MaxTypeAlignStr = "-fmax-type-align=16";
4644       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4645     }
4646   }
4647 
4648   if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4649     CmdArgs.push_back("-Qn");
4650 
4651   // -fcommon is the default unless compiling kernel code or the target says so
4652   bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
4653   if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4654                     !NoCommonDefault))
4655     CmdArgs.push_back("-fno-common");
4656 
4657   // -fsigned-bitfields is default, and clang doesn't yet support
4658   // -funsigned-bitfields.
4659   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4660                     options::OPT_funsigned_bitfields))
4661     D.Diag(diag::warn_drv_clang_unsupported)
4662         << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4663 
4664   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4665   if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4666     D.Diag(diag::err_drv_clang_unsupported)
4667         << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4668 
4669   // -finput_charset=UTF-8 is default. Reject others
4670   if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4671     StringRef value = inputCharset->getValue();
4672     if (!value.equals_lower("utf-8"))
4673       D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4674                                           << value;
4675   }
4676 
4677   // -fexec_charset=UTF-8 is default. Reject others
4678   if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4679     StringRef value = execCharset->getValue();
4680     if (!value.equals_lower("utf-8"))
4681       D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4682                                           << value;
4683   }
4684 
4685   RenderDiagnosticsOptions(D, Args, CmdArgs);
4686 
4687   // -fno-asm-blocks is default.
4688   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4689                    false))
4690     CmdArgs.push_back("-fasm-blocks");
4691 
4692   // -fgnu-inline-asm is default.
4693   if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4694                     options::OPT_fno_gnu_inline_asm, true))
4695     CmdArgs.push_back("-fno-gnu-inline-asm");
4696 
4697   // Enable vectorization per default according to the optimization level
4698   // selected. For optimization levels that want vectorization we use the alias
4699   // option to simplify the hasFlag logic.
4700   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4701   OptSpecifier VectorizeAliasOption =
4702       EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4703   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4704                    options::OPT_fno_vectorize, EnableVec))
4705     CmdArgs.push_back("-vectorize-loops");
4706 
4707   // -fslp-vectorize is enabled based on the optimization level selected.
4708   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4709   OptSpecifier SLPVectAliasOption =
4710       EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4711   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4712                    options::OPT_fno_slp_vectorize, EnableSLPVec))
4713     CmdArgs.push_back("-vectorize-slp");
4714 
4715   ParseMPreferVectorWidth(D, Args, CmdArgs);
4716 
4717   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4718     A->render(Args, CmdArgs);
4719 
4720   if (Arg *A = Args.getLastArg(
4721           options::OPT_fsanitize_undefined_strip_path_components_EQ))
4722     A->render(Args, CmdArgs);
4723 
4724   // -fdollars-in-identifiers default varies depending on platform and
4725   // language; only pass if specified.
4726   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4727                                options::OPT_fno_dollars_in_identifiers)) {
4728     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4729       CmdArgs.push_back("-fdollars-in-identifiers");
4730     else
4731       CmdArgs.push_back("-fno-dollars-in-identifiers");
4732   }
4733 
4734   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4735   // practical purposes.
4736   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4737                                options::OPT_fno_unit_at_a_time)) {
4738     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4739       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4740   }
4741 
4742   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4743                    options::OPT_fno_apple_pragma_pack, false))
4744     CmdArgs.push_back("-fapple-pragma-pack");
4745 
4746   if (Args.hasFlag(options::OPT_fsave_optimization_record,
4747                    options::OPT_foptimization_record_file_EQ,
4748                    options::OPT_fno_save_optimization_record, false)) {
4749     CmdArgs.push_back("-opt-record-file");
4750 
4751     const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4752     if (A) {
4753       CmdArgs.push_back(A->getValue());
4754     } else {
4755       SmallString<128> F;
4756 
4757       if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4758         if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4759           F = FinalOutput->getValue();
4760       }
4761 
4762       if (F.empty()) {
4763         // Use the input filename.
4764         F = llvm::sys::path::stem(Input.getBaseInput());
4765 
4766         // If we're compiling for an offload architecture (i.e. a CUDA device),
4767         // we need to make the file name for the device compilation different
4768         // from the host compilation.
4769         if (!JA.isDeviceOffloading(Action::OFK_None) &&
4770             !JA.isDeviceOffloading(Action::OFK_Host)) {
4771           llvm::sys::path::replace_extension(F, "");
4772           F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4773                                                    Triple.normalize());
4774           F += "-";
4775           F += JA.getOffloadingArch();
4776         }
4777       }
4778 
4779       llvm::sys::path::replace_extension(F, "opt.yaml");
4780       CmdArgs.push_back(Args.MakeArgString(F));
4781     }
4782   }
4783 
4784   bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4785                                      options::OPT_fno_rewrite_imports, false);
4786   if (RewriteImports)
4787     CmdArgs.push_back("-frewrite-imports");
4788 
4789   // Enable rewrite includes if the user's asked for it or if we're generating
4790   // diagnostics.
4791   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4792   // nice to enable this when doing a crashdump for modules as well.
4793   if (Args.hasFlag(options::OPT_frewrite_includes,
4794                    options::OPT_fno_rewrite_includes, false) ||
4795       (C.isForDiagnostics() && (RewriteImports || !HaveModules)))
4796     CmdArgs.push_back("-frewrite-includes");
4797 
4798   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4799   if (Arg *A = Args.getLastArg(options::OPT_traditional,
4800                                options::OPT_traditional_cpp)) {
4801     if (isa<PreprocessJobAction>(JA))
4802       CmdArgs.push_back("-traditional-cpp");
4803     else
4804       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4805   }
4806 
4807   Args.AddLastArg(CmdArgs, options::OPT_dM);
4808   Args.AddLastArg(CmdArgs, options::OPT_dD);
4809 
4810   // Handle serialized diagnostics.
4811   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4812     CmdArgs.push_back("-serialize-diagnostic-file");
4813     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4814   }
4815 
4816   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4817     CmdArgs.push_back("-fretain-comments-from-system-headers");
4818 
4819   // Forward -fcomment-block-commands to -cc1.
4820   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4821   // Forward -fparse-all-comments to -cc1.
4822   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4823 
4824   // Turn -fplugin=name.so into -load name.so
4825   for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4826     CmdArgs.push_back("-load");
4827     CmdArgs.push_back(A->getValue());
4828     A->claim();
4829   }
4830 
4831   // Setup statistics file output.
4832   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
4833   if (!StatsFile.empty())
4834     CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
4835 
4836   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4837   // parser.
4838   // -finclude-default-header flag is for preprocessor,
4839   // do not pass it to other cc1 commands when save-temps is enabled
4840   if (C.getDriver().isSaveTempsEnabled() &&
4841       !isa<PreprocessJobAction>(JA)) {
4842     for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4843       Arg->claim();
4844       if (StringRef(Arg->getValue()) != "-finclude-default-header")
4845         CmdArgs.push_back(Arg->getValue());
4846     }
4847   }
4848   else {
4849     Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4850   }
4851   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4852     A->claim();
4853 
4854     // We translate this by hand to the -cc1 argument, since nightly test uses
4855     // it and developers have been trained to spell it with -mllvm. Both
4856     // spellings are now deprecated and should be removed.
4857     if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4858       CmdArgs.push_back("-disable-llvm-optzns");
4859     } else {
4860       A->render(Args, CmdArgs);
4861     }
4862   }
4863 
4864   // With -save-temps, we want to save the unoptimized bitcode output from the
4865   // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4866   // by the frontend.
4867   // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4868   // has slightly different breakdown between stages.
4869   // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4870   // pristine IR generated by the frontend. Ideally, a new compile action should
4871   // be added so both IR can be captured.
4872   if (C.getDriver().isSaveTempsEnabled() &&
4873       !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4874       isa<CompileJobAction>(JA))
4875     CmdArgs.push_back("-disable-llvm-passes");
4876 
4877   if (Output.getType() == types::TY_Dependencies) {
4878     // Handled with other dependency code.
4879   } else if (Output.isFilename()) {
4880     CmdArgs.push_back("-o");
4881     CmdArgs.push_back(Output.getFilename());
4882   } else {
4883     assert(Output.isNothing() && "Invalid output.");
4884   }
4885 
4886   addDashXForInput(Args, Input, CmdArgs);
4887 
4888   ArrayRef<InputInfo> FrontendInputs = Input;
4889   if (IsHeaderModulePrecompile)
4890     FrontendInputs = ModuleHeaderInputs;
4891   else if (Input.isNothing())
4892     FrontendInputs = {};
4893 
4894   for (const InputInfo &Input : FrontendInputs) {
4895     if (Input.isFilename())
4896       CmdArgs.push_back(Input.getFilename());
4897     else
4898       Input.getInputArg().renderAsInput(Args, CmdArgs);
4899   }
4900 
4901   Args.AddAllArgs(CmdArgs, options::OPT_undef);
4902 
4903   const char *Exec = D.getClangProgramPath();
4904 
4905   // Optionally embed the -cc1 level arguments into the debug info, for build
4906   // analysis.
4907   // Also record command line arguments into the debug info if
4908   // -grecord-gcc-switches options is set on.
4909   // By default, -gno-record-gcc-switches is set on and no recording.
4910   if (TC.UseDwarfDebugFlags() ||
4911       Args.hasFlag(options::OPT_grecord_gcc_switches,
4912                    options::OPT_gno_record_gcc_switches, false)) {
4913     ArgStringList OriginalArgs;
4914     for (const auto &Arg : Args)
4915       Arg->render(Args, OriginalArgs);
4916 
4917     SmallString<256> Flags;
4918     Flags += Exec;
4919     for (const char *OriginalArg : OriginalArgs) {
4920       SmallString<128> EscapedArg;
4921       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4922       Flags += " ";
4923       Flags += EscapedArg;
4924     }
4925     CmdArgs.push_back("-dwarf-debug-flags");
4926     CmdArgs.push_back(Args.MakeArgString(Flags));
4927   }
4928 
4929   // Host-side cuda compilation receives all device-side outputs in a single
4930   // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
4931   if ((IsCuda || IsHIP) && CudaDeviceInput) {
4932       CmdArgs.push_back("-fcuda-include-gpubinary");
4933       CmdArgs.push_back(CudaDeviceInput->getFilename());
4934       if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
4935         CmdArgs.push_back("-fgpu-rdc");
4936   }
4937 
4938   if (IsCuda) {
4939     if (Args.hasFlag(options::OPT_fcuda_short_ptr,
4940                      options::OPT_fno_cuda_short_ptr, false))
4941       CmdArgs.push_back("-fcuda-short-ptr");
4942   }
4943 
4944   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4945   // to specify the result of the compile phase on the host, so the meaningful
4946   // device declarations can be identified. Also, -fopenmp-is-device is passed
4947   // along to tell the frontend that it is generating code for a device, so that
4948   // only the relevant declarations are emitted.
4949   if (IsOpenMPDevice) {
4950     CmdArgs.push_back("-fopenmp-is-device");
4951     if (OpenMPDeviceInput) {
4952       CmdArgs.push_back("-fopenmp-host-ir-file-path");
4953       CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
4954     }
4955   }
4956 
4957   // For all the host OpenMP offloading compile jobs we need to pass the targets
4958   // information using -fopenmp-targets= option.
4959   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
4960     SmallString<128> TargetInfo("-fopenmp-targets=");
4961 
4962     Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4963     assert(Tgts && Tgts->getNumValues() &&
4964            "OpenMP offloading has to have targets specified.");
4965     for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4966       if (i)
4967         TargetInfo += ',';
4968       // We need to get the string from the triple because it may be not exactly
4969       // the same as the one we get directly from the arguments.
4970       llvm::Triple T(Tgts->getValue(i));
4971       TargetInfo += T.getTriple();
4972     }
4973     CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4974   }
4975 
4976   bool WholeProgramVTables =
4977       Args.hasFlag(options::OPT_fwhole_program_vtables,
4978                    options::OPT_fno_whole_program_vtables, false);
4979   if (WholeProgramVTables) {
4980     if (!D.isUsingLTO())
4981       D.Diag(diag::err_drv_argument_only_allowed_with)
4982           << "-fwhole-program-vtables"
4983           << "-flto";
4984     CmdArgs.push_back("-fwhole-program-vtables");
4985   }
4986 
4987   if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
4988                                options::OPT_fno_experimental_isel)) {
4989     CmdArgs.push_back("-mllvm");
4990     if (A->getOption().matches(options::OPT_fexperimental_isel)) {
4991       CmdArgs.push_back("-global-isel=1");
4992 
4993       // GISel is on by default on AArch64 -O0, so don't bother adding
4994       // the fallback remarks for it. Other combinations will add a warning of
4995       // some kind.
4996       bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
4997       bool IsOptLevelSupported = false;
4998 
4999       Arg *A = Args.getLastArg(options::OPT_O_Group);
5000       if (Triple.getArch() == llvm::Triple::aarch64) {
5001         if (!A || A->getOption().matches(options::OPT_O0))
5002           IsOptLevelSupported = true;
5003       }
5004       if (!IsArchSupported || !IsOptLevelSupported) {
5005         CmdArgs.push_back("-mllvm");
5006         CmdArgs.push_back("-global-isel-abort=2");
5007 
5008         if (!IsArchSupported)
5009           D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5010         else
5011           D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5012       }
5013     } else {
5014       CmdArgs.push_back("-global-isel=0");
5015     }
5016   }
5017 
5018   if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5019                                options::OPT_fno_force_enable_int128)) {
5020     if (A->getOption().matches(options::OPT_fforce_enable_int128))
5021       CmdArgs.push_back("-fforce-enable-int128");
5022   }
5023 
5024   if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5025                    options::OPT_fno_complete_member_pointers, false))
5026     CmdArgs.push_back("-fcomplete-member-pointers");
5027 
5028   if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5029                     options::OPT_fno_cxx_static_destructors, true))
5030     CmdArgs.push_back("-fno-c++-static-destructors");
5031 
5032   if (Arg *A = Args.getLastArg(options::OPT_moutline,
5033                                options::OPT_mno_outline)) {
5034     if (A->getOption().matches(options::OPT_moutline)) {
5035       // We only support -moutline in AArch64 right now. If we're not compiling
5036       // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5037       // proper mllvm flags.
5038       if (Triple.getArch() != llvm::Triple::aarch64) {
5039         D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5040       } else {
5041           CmdArgs.push_back("-mllvm");
5042           CmdArgs.push_back("-enable-machine-outliner");
5043       }
5044     } else {
5045       // Disable all outlining behaviour.
5046       CmdArgs.push_back("-mllvm");
5047       CmdArgs.push_back("-enable-machine-outliner=never");
5048     }
5049   }
5050 
5051   if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
5052                    (TC.getTriple().isOSBinFormatELF() ||
5053                     TC.getTriple().isOSBinFormatCOFF()) &&
5054                        TC.useIntegratedAs()))
5055     CmdArgs.push_back("-faddrsig");
5056 
5057   // Finally add the compile command to the compilation.
5058   if (Args.hasArg(options::OPT__SLASH_fallback) &&
5059       Output.getType() == types::TY_Object &&
5060       (InputType == types::TY_C || InputType == types::TY_CXX)) {
5061     auto CLCommand =
5062         getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5063     C.addCommand(llvm::make_unique<FallbackCommand>(
5064         JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5065   } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5066              isa<PrecompileJobAction>(JA)) {
5067     // In /fallback builds, run the main compilation even if the pch generation
5068     // fails, so that the main compilation's fallback to cl.exe runs.
5069     C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
5070                                                         CmdArgs, Inputs));
5071   } else {
5072     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5073   }
5074 
5075   // Make the compile command echo its inputs for /showFilenames.
5076   if (Output.getType() == types::TY_Object &&
5077       Args.hasFlag(options::OPT__SLASH_showFilenames,
5078                    options::OPT__SLASH_showFilenames_, false)) {
5079     C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5080   }
5081 
5082   if (Arg *A = Args.getLastArg(options::OPT_pg))
5083     if (!shouldUseFramePointer(Args, Triple))
5084       D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5085                                                       << A->getAsString(Args);
5086 
5087   // Claim some arguments which clang supports automatically.
5088 
5089   // -fpch-preprocess is used with gcc to add a special marker in the output to
5090   // include the PCH file. Clang's PTH solution is completely transparent, so we
5091   // do not need to deal with it at all.
5092   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5093 
5094   // Claim some arguments which clang doesn't support, but we don't
5095   // care to warn the user about.
5096   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5097   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5098 
5099   // Disable warnings for clang -E -emit-llvm foo.c
5100   Args.ClaimAllArgs(options::OPT_emit_llvm);
5101 }
5102 
5103 Clang::Clang(const ToolChain &TC)
5104     // CAUTION! The first constructor argument ("clang") is not arbitrary,
5105     // as it is for other tools. Some operations on a Tool actually test
5106     // whether that tool is Clang based on the Tool's Name as a string.
5107     : Tool("clang", "clang frontend", TC, RF_Full) {}
5108 
5109 Clang::~Clang() {}
5110 
5111 /// Add options related to the Objective-C runtime/ABI.
5112 ///
5113 /// Returns true if the runtime is non-fragile.
5114 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5115                                       ArgStringList &cmdArgs,
5116                                       RewriteKind rewriteKind) const {
5117   // Look for the controlling runtime option.
5118   Arg *runtimeArg =
5119       args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5120                       options::OPT_fobjc_runtime_EQ);
5121 
5122   // Just forward -fobjc-runtime= to the frontend.  This supercedes
5123   // options about fragility.
5124   if (runtimeArg &&
5125       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5126     ObjCRuntime runtime;
5127     StringRef value = runtimeArg->getValue();
5128     if (runtime.tryParse(value)) {
5129       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5130           << value;
5131     }
5132     if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5133         (runtime.getVersion() >= VersionTuple(2, 0)))
5134       if (!getToolChain().getTriple().isOSBinFormatELF() &&
5135           !getToolChain().getTriple().isOSBinFormatCOFF()) {
5136         getToolChain().getDriver().Diag(
5137             diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5138           << runtime.getVersion().getMajor();
5139       }
5140 
5141     runtimeArg->render(args, cmdArgs);
5142     return runtime;
5143   }
5144 
5145   // Otherwise, we'll need the ABI "version".  Version numbers are
5146   // slightly confusing for historical reasons:
5147   //   1 - Traditional "fragile" ABI
5148   //   2 - Non-fragile ABI, version 1
5149   //   3 - Non-fragile ABI, version 2
5150   unsigned objcABIVersion = 1;
5151   // If -fobjc-abi-version= is present, use that to set the version.
5152   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5153     StringRef value = abiArg->getValue();
5154     if (value == "1")
5155       objcABIVersion = 1;
5156     else if (value == "2")
5157       objcABIVersion = 2;
5158     else if (value == "3")
5159       objcABIVersion = 3;
5160     else
5161       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5162   } else {
5163     // Otherwise, determine if we are using the non-fragile ABI.
5164     bool nonFragileABIIsDefault =
5165         (rewriteKind == RK_NonFragile ||
5166          (rewriteKind == RK_None &&
5167           getToolChain().IsObjCNonFragileABIDefault()));
5168     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5169                      options::OPT_fno_objc_nonfragile_abi,
5170                      nonFragileABIIsDefault)) {
5171 // Determine the non-fragile ABI version to use.
5172 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5173       unsigned nonFragileABIVersion = 1;
5174 #else
5175       unsigned nonFragileABIVersion = 2;
5176 #endif
5177 
5178       if (Arg *abiArg =
5179               args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5180         StringRef value = abiArg->getValue();
5181         if (value == "1")
5182           nonFragileABIVersion = 1;
5183         else if (value == "2")
5184           nonFragileABIVersion = 2;
5185         else
5186           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5187               << value;
5188       }
5189 
5190       objcABIVersion = 1 + nonFragileABIVersion;
5191     } else {
5192       objcABIVersion = 1;
5193     }
5194   }
5195 
5196   // We don't actually care about the ABI version other than whether
5197   // it's non-fragile.
5198   bool isNonFragile = objcABIVersion != 1;
5199 
5200   // If we have no runtime argument, ask the toolchain for its default runtime.
5201   // However, the rewriter only really supports the Mac runtime, so assume that.
5202   ObjCRuntime runtime;
5203   if (!runtimeArg) {
5204     switch (rewriteKind) {
5205     case RK_None:
5206       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5207       break;
5208     case RK_Fragile:
5209       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5210       break;
5211     case RK_NonFragile:
5212       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5213       break;
5214     }
5215 
5216     // -fnext-runtime
5217   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5218     // On Darwin, make this use the default behavior for the toolchain.
5219     if (getToolChain().getTriple().isOSDarwin()) {
5220       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5221 
5222       // Otherwise, build for a generic macosx port.
5223     } else {
5224       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5225     }
5226 
5227     // -fgnu-runtime
5228   } else {
5229     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5230     // Legacy behaviour is to target the gnustep runtime if we are in
5231     // non-fragile mode or the GCC runtime in fragile mode.
5232     if (isNonFragile)
5233       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
5234     else
5235       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5236   }
5237 
5238   cmdArgs.push_back(
5239       args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5240   return runtime;
5241 }
5242 
5243 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5244   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5245   I += HaveDash;
5246   return !HaveDash;
5247 }
5248 
5249 namespace {
5250 struct EHFlags {
5251   bool Synch = false;
5252   bool Asynch = false;
5253   bool NoUnwindC = false;
5254 };
5255 } // end anonymous namespace
5256 
5257 /// /EH controls whether to run destructor cleanups when exceptions are
5258 /// thrown.  There are three modifiers:
5259 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5260 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5261 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5262 /// - c: Assume that extern "C" functions are implicitly nounwind.
5263 /// The default is /EHs-c-, meaning cleanups are disabled.
5264 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5265   EHFlags EH;
5266 
5267   std::vector<std::string> EHArgs =
5268       Args.getAllArgValues(options::OPT__SLASH_EH);
5269   for (auto EHVal : EHArgs) {
5270     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5271       switch (EHVal[I]) {
5272       case 'a':
5273         EH.Asynch = maybeConsumeDash(EHVal, I);
5274         if (EH.Asynch)
5275           EH.Synch = false;
5276         continue;
5277       case 'c':
5278         EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5279         continue;
5280       case 's':
5281         EH.Synch = maybeConsumeDash(EHVal, I);
5282         if (EH.Synch)
5283           EH.Asynch = false;
5284         continue;
5285       default:
5286         break;
5287       }
5288       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5289       break;
5290     }
5291   }
5292   // The /GX, /GX- flags are only processed if there are not /EH flags.
5293   // The default is that /GX is not specified.
5294   if (EHArgs.empty() &&
5295       Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5296                    /*default=*/false)) {
5297     EH.Synch = true;
5298     EH.NoUnwindC = true;
5299   }
5300 
5301   return EH;
5302 }
5303 
5304 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5305                            ArgStringList &CmdArgs,
5306                            codegenoptions::DebugInfoKind *DebugInfoKind,
5307                            bool *EmitCodeView) const {
5308   unsigned RTOptionID = options::OPT__SLASH_MT;
5309 
5310   if (Args.hasArg(options::OPT__SLASH_LDd))
5311     // The /LDd option implies /MTd. The dependent lib part can be overridden,
5312     // but defining _DEBUG is sticky.
5313     RTOptionID = options::OPT__SLASH_MTd;
5314 
5315   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5316     RTOptionID = A->getOption().getID();
5317 
5318   StringRef FlagForCRT;
5319   switch (RTOptionID) {
5320   case options::OPT__SLASH_MD:
5321     if (Args.hasArg(options::OPT__SLASH_LDd))
5322       CmdArgs.push_back("-D_DEBUG");
5323     CmdArgs.push_back("-D_MT");
5324     CmdArgs.push_back("-D_DLL");
5325     FlagForCRT = "--dependent-lib=msvcrt";
5326     break;
5327   case options::OPT__SLASH_MDd:
5328     CmdArgs.push_back("-D_DEBUG");
5329     CmdArgs.push_back("-D_MT");
5330     CmdArgs.push_back("-D_DLL");
5331     FlagForCRT = "--dependent-lib=msvcrtd";
5332     break;
5333   case options::OPT__SLASH_MT:
5334     if (Args.hasArg(options::OPT__SLASH_LDd))
5335       CmdArgs.push_back("-D_DEBUG");
5336     CmdArgs.push_back("-D_MT");
5337     CmdArgs.push_back("-flto-visibility-public-std");
5338     FlagForCRT = "--dependent-lib=libcmt";
5339     break;
5340   case options::OPT__SLASH_MTd:
5341     CmdArgs.push_back("-D_DEBUG");
5342     CmdArgs.push_back("-D_MT");
5343     CmdArgs.push_back("-flto-visibility-public-std");
5344     FlagForCRT = "--dependent-lib=libcmtd";
5345     break;
5346   default:
5347     llvm_unreachable("Unexpected option ID.");
5348   }
5349 
5350   if (Args.hasArg(options::OPT__SLASH_Zl)) {
5351     CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5352   } else {
5353     CmdArgs.push_back(FlagForCRT.data());
5354 
5355     // This provides POSIX compatibility (maps 'open' to '_open'), which most
5356     // users want.  The /Za flag to cl.exe turns this off, but it's not
5357     // implemented in clang.
5358     CmdArgs.push_back("--dependent-lib=oldnames");
5359   }
5360 
5361   if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5362     A->render(Args, CmdArgs);
5363 
5364   // This controls whether or not we emit RTTI data for polymorphic types.
5365   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5366                    /*default=*/false))
5367     CmdArgs.push_back("-fno-rtti-data");
5368 
5369   // This controls whether or not we emit stack-protector instrumentation.
5370   // In MSVC, Buffer Security Check (/GS) is on by default.
5371   if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5372                    /*default=*/true)) {
5373     CmdArgs.push_back("-stack-protector");
5374     CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5375   }
5376 
5377   // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5378   if (Arg *DebugInfoArg =
5379           Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5380                           options::OPT_gline_tables_only)) {
5381     *EmitCodeView = true;
5382     if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5383       *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5384     else
5385       *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5386     CmdArgs.push_back("-gcodeview");
5387   } else {
5388     *EmitCodeView = false;
5389   }
5390 
5391   const Driver &D = getToolChain().getDriver();
5392   EHFlags EH = parseClangCLEHFlags(D, Args);
5393   if (EH.Synch || EH.Asynch) {
5394     if (types::isCXX(InputType))
5395       CmdArgs.push_back("-fcxx-exceptions");
5396     CmdArgs.push_back("-fexceptions");
5397   }
5398   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5399     CmdArgs.push_back("-fexternc-nounwind");
5400 
5401   // /EP should expand to -E -P.
5402   if (Args.hasArg(options::OPT__SLASH_EP)) {
5403     CmdArgs.push_back("-E");
5404     CmdArgs.push_back("-P");
5405   }
5406 
5407   unsigned VolatileOptionID;
5408   if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5409       getToolChain().getArch() == llvm::Triple::x86)
5410     VolatileOptionID = options::OPT__SLASH_volatile_ms;
5411   else
5412     VolatileOptionID = options::OPT__SLASH_volatile_iso;
5413 
5414   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5415     VolatileOptionID = A->getOption().getID();
5416 
5417   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5418     CmdArgs.push_back("-fms-volatile");
5419 
5420   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5421   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5422   if (MostGeneralArg && BestCaseArg)
5423     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5424         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5425 
5426   if (MostGeneralArg) {
5427     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5428     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5429     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5430 
5431     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5432     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5433     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5434       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5435           << FirstConflict->getAsString(Args)
5436           << SecondConflict->getAsString(Args);
5437 
5438     if (SingleArg)
5439       CmdArgs.push_back("-fms-memptr-rep=single");
5440     else if (MultipleArg)
5441       CmdArgs.push_back("-fms-memptr-rep=multiple");
5442     else
5443       CmdArgs.push_back("-fms-memptr-rep=virtual");
5444   }
5445 
5446   // Parse the default calling convention options.
5447   if (Arg *CCArg =
5448           Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
5449                           options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5450                           options::OPT__SLASH_Gregcall)) {
5451     unsigned DCCOptId = CCArg->getOption().getID();
5452     const char *DCCFlag = nullptr;
5453     bool ArchSupported = true;
5454     llvm::Triple::ArchType Arch = getToolChain().getArch();
5455     switch (DCCOptId) {
5456     case options::OPT__SLASH_Gd:
5457       DCCFlag = "-fdefault-calling-conv=cdecl";
5458       break;
5459     case options::OPT__SLASH_Gr:
5460       ArchSupported = Arch == llvm::Triple::x86;
5461       DCCFlag = "-fdefault-calling-conv=fastcall";
5462       break;
5463     case options::OPT__SLASH_Gz:
5464       ArchSupported = Arch == llvm::Triple::x86;
5465       DCCFlag = "-fdefault-calling-conv=stdcall";
5466       break;
5467     case options::OPT__SLASH_Gv:
5468       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5469       DCCFlag = "-fdefault-calling-conv=vectorcall";
5470       break;
5471     case options::OPT__SLASH_Gregcall:
5472       ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5473       DCCFlag = "-fdefault-calling-conv=regcall";
5474       break;
5475     }
5476 
5477     // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5478     if (ArchSupported && DCCFlag)
5479       CmdArgs.push_back(DCCFlag);
5480   }
5481 
5482   if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5483     A->render(Args, CmdArgs);
5484 
5485   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5486     CmdArgs.push_back("-fdiagnostics-format");
5487     if (Args.hasArg(options::OPT__SLASH_fallback))
5488       CmdArgs.push_back("msvc-fallback");
5489     else
5490       CmdArgs.push_back("msvc");
5491   }
5492 
5493   if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5494     SmallVector<StringRef, 1> SplitArgs;
5495     StringRef(A->getValue()).split(SplitArgs, ",");
5496     bool Instrument = false;
5497     bool NoChecks = false;
5498     for (StringRef Arg : SplitArgs) {
5499       if (Arg.equals_lower("cf"))
5500         Instrument = true;
5501       else if (Arg.equals_lower("cf-"))
5502         Instrument = false;
5503       else if (Arg.equals_lower("nochecks"))
5504         NoChecks = true;
5505       else if (Arg.equals_lower("nochecks-"))
5506         NoChecks = false;
5507       else
5508         D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5509     }
5510     // Currently there's no support emitting CFG instrumentation; the flag only
5511     // emits the table of address-taken functions.
5512     if (Instrument || NoChecks)
5513       CmdArgs.push_back("-cfguard");
5514   }
5515 }
5516 
5517 visualstudio::Compiler *Clang::getCLFallback() const {
5518   if (!CLFallback)
5519     CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5520   return CLFallback.get();
5521 }
5522 
5523 
5524 const char *Clang::getBaseInputName(const ArgList &Args,
5525                                     const InputInfo &Input) {
5526   return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5527 }
5528 
5529 const char *Clang::getBaseInputStem(const ArgList &Args,
5530                                     const InputInfoList &Inputs) {
5531   const char *Str = getBaseInputName(Args, Inputs[0]);
5532 
5533   if (const char *End = strrchr(Str, '.'))
5534     return Args.MakeArgString(std::string(Str, End));
5535 
5536   return Str;
5537 }
5538 
5539 const char *Clang::getDependencyFileName(const ArgList &Args,
5540                                          const InputInfoList &Inputs) {
5541   // FIXME: Think about this more.
5542   std::string Res;
5543 
5544   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5545     std::string Str(OutputOpt->getValue());
5546     Res = Str.substr(0, Str.rfind('.'));
5547   } else {
5548     Res = getBaseInputStem(Args, Inputs);
5549   }
5550   return Args.MakeArgString(Res + ".d");
5551 }
5552 
5553 // Begin ClangAs
5554 
5555 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5556                                 ArgStringList &CmdArgs) const {
5557   StringRef CPUName;
5558   StringRef ABIName;
5559   const llvm::Triple &Triple = getToolChain().getTriple();
5560   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5561 
5562   CmdArgs.push_back("-target-abi");
5563   CmdArgs.push_back(ABIName.data());
5564 }
5565 
5566 void ClangAs::AddX86TargetArgs(const ArgList &Args,
5567                                ArgStringList &CmdArgs) const {
5568   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5569     StringRef Value = A->getValue();
5570     if (Value == "intel" || Value == "att") {
5571       CmdArgs.push_back("-mllvm");
5572       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5573     } else {
5574       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5575           << A->getOption().getName() << Value;
5576     }
5577   }
5578 }
5579 
5580 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5581                            const InputInfo &Output, const InputInfoList &Inputs,
5582                            const ArgList &Args,
5583                            const char *LinkingOutput) const {
5584   ArgStringList CmdArgs;
5585 
5586   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5587   const InputInfo &Input = Inputs[0];
5588 
5589   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5590   const std::string &TripleStr = Triple.getTriple();
5591   const auto &D = getToolChain().getDriver();
5592 
5593   // Don't warn about "clang -w -c foo.s"
5594   Args.ClaimAllArgs(options::OPT_w);
5595   // and "clang -emit-llvm -c foo.s"
5596   Args.ClaimAllArgs(options::OPT_emit_llvm);
5597 
5598   claimNoWarnArgs(Args);
5599 
5600   // Invoke ourselves in -cc1as mode.
5601   //
5602   // FIXME: Implement custom jobs for internal actions.
5603   CmdArgs.push_back("-cc1as");
5604 
5605   // Add the "effective" target triple.
5606   CmdArgs.push_back("-triple");
5607   CmdArgs.push_back(Args.MakeArgString(TripleStr));
5608 
5609   // Set the output mode, we currently only expect to be used as a real
5610   // assembler.
5611   CmdArgs.push_back("-filetype");
5612   CmdArgs.push_back("obj");
5613 
5614   // Set the main file name, so that debug info works even with
5615   // -save-temps or preprocessed assembly.
5616   CmdArgs.push_back("-main-file-name");
5617   CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5618 
5619   // Add the target cpu
5620   std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5621   if (!CPU.empty()) {
5622     CmdArgs.push_back("-target-cpu");
5623     CmdArgs.push_back(Args.MakeArgString(CPU));
5624   }
5625 
5626   // Add the target features
5627   getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5628 
5629   // Ignore explicit -force_cpusubtype_ALL option.
5630   (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5631 
5632   // Pass along any -I options so we get proper .include search paths.
5633   Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5634 
5635   // Determine the original source input.
5636   const Action *SourceAction = &JA;
5637   while (SourceAction->getKind() != Action::InputClass) {
5638     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5639     SourceAction = SourceAction->getInputs()[0];
5640   }
5641 
5642   // Forward -g and handle debug info related flags, assuming we are dealing
5643   // with an actual assembly file.
5644   bool WantDebug = false;
5645   unsigned DwarfVersion = 0;
5646   Args.ClaimAllArgs(options::OPT_g_Group);
5647   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5648     WantDebug = !A->getOption().matches(options::OPT_g0) &&
5649                 !A->getOption().matches(options::OPT_ggdb0);
5650     if (WantDebug)
5651       DwarfVersion = DwarfVersionNum(A->getSpelling());
5652   }
5653   if (DwarfVersion == 0)
5654     DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5655 
5656   codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5657 
5658   if (SourceAction->getType() == types::TY_Asm ||
5659       SourceAction->getType() == types::TY_PP_Asm) {
5660     // You might think that it would be ok to set DebugInfoKind outside of
5661     // the guard for source type, however there is a test which asserts
5662     // that some assembler invocation receives no -debug-info-kind,
5663     // and it's not clear whether that test is just overly restrictive.
5664     DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5665                                : codegenoptions::NoDebugInfo);
5666     // Add the -fdebug-compilation-dir flag if needed.
5667     addDebugCompDirArg(Args, CmdArgs);
5668 
5669     addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
5670 
5671     // Set the AT_producer to the clang version when using the integrated
5672     // assembler on assembly source files.
5673     CmdArgs.push_back("-dwarf-debug-producer");
5674     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5675 
5676     // And pass along -I options
5677     Args.AddAllArgs(CmdArgs, options::OPT_I);
5678   }
5679   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5680                           llvm::DebuggerKind::Default);
5681   RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
5682 
5683 
5684   // Handle -fPIC et al -- the relocation-model affects the assembler
5685   // for some targets.
5686   llvm::Reloc::Model RelocationModel;
5687   unsigned PICLevel;
5688   bool IsPIE;
5689   std::tie(RelocationModel, PICLevel, IsPIE) =
5690       ParsePICArgs(getToolChain(), Args);
5691 
5692   const char *RMName = RelocationModelName(RelocationModel);
5693   if (RMName) {
5694     CmdArgs.push_back("-mrelocation-model");
5695     CmdArgs.push_back(RMName);
5696   }
5697 
5698   // Optionally embed the -cc1as level arguments into the debug info, for build
5699   // analysis.
5700   if (getToolChain().UseDwarfDebugFlags()) {
5701     ArgStringList OriginalArgs;
5702     for (const auto &Arg : Args)
5703       Arg->render(Args, OriginalArgs);
5704 
5705     SmallString<256> Flags;
5706     const char *Exec = getToolChain().getDriver().getClangProgramPath();
5707     Flags += Exec;
5708     for (const char *OriginalArg : OriginalArgs) {
5709       SmallString<128> EscapedArg;
5710       EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5711       Flags += " ";
5712       Flags += EscapedArg;
5713     }
5714     CmdArgs.push_back("-dwarf-debug-flags");
5715     CmdArgs.push_back(Args.MakeArgString(Flags));
5716   }
5717 
5718   // FIXME: Add -static support, once we have it.
5719 
5720   // Add target specific flags.
5721   switch (getToolChain().getArch()) {
5722   default:
5723     break;
5724 
5725   case llvm::Triple::mips:
5726   case llvm::Triple::mipsel:
5727   case llvm::Triple::mips64:
5728   case llvm::Triple::mips64el:
5729     AddMIPSTargetArgs(Args, CmdArgs);
5730     break;
5731 
5732   case llvm::Triple::x86:
5733   case llvm::Triple::x86_64:
5734     AddX86TargetArgs(Args, CmdArgs);
5735     break;
5736 
5737   case llvm::Triple::arm:
5738   case llvm::Triple::armeb:
5739   case llvm::Triple::thumb:
5740   case llvm::Triple::thumbeb:
5741     // This isn't in AddARMTargetArgs because we want to do this for assembly
5742     // only, not C/C++.
5743     if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5744                      options::OPT_mno_default_build_attributes, true)) {
5745         CmdArgs.push_back("-mllvm");
5746         CmdArgs.push_back("-arm-add-build-attributes");
5747     }
5748     break;
5749   }
5750 
5751   // Consume all the warning flags. Usually this would be handled more
5752   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5753   // doesn't handle that so rather than warning about unused flags that are
5754   // actually used, we'll lie by omission instead.
5755   // FIXME: Stop lying and consume only the appropriate driver flags
5756   Args.ClaimAllArgs(options::OPT_W_Group);
5757 
5758   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5759                                     getToolChain().getDriver());
5760 
5761   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5762 
5763   assert(Output.isFilename() && "Unexpected lipo output.");
5764   CmdArgs.push_back("-o");
5765   CmdArgs.push_back(Output.getFilename());
5766 
5767   const llvm::Triple &T = getToolChain().getTriple();
5768   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5769       (T.isOSLinux() || T.isOSFuchsia())) {
5770     CmdArgs.push_back("-split-dwarf-file");
5771     CmdArgs.push_back(SplitDebugName(Args, Input));
5772   }
5773 
5774   assert(Input.isFilename() && "Invalid input.");
5775   CmdArgs.push_back(Input.getFilename());
5776 
5777   const char *Exec = getToolChain().getDriver().getClangProgramPath();
5778   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5779 }
5780 
5781 // Begin OffloadBundler
5782 
5783 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5784                                   const InputInfo &Output,
5785                                   const InputInfoList &Inputs,
5786                                   const llvm::opt::ArgList &TCArgs,
5787                                   const char *LinkingOutput) const {
5788   // The version with only one output is expected to refer to a bundling job.
5789   assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5790 
5791   // The bundling command looks like this:
5792   // clang-offload-bundler -type=bc
5793   //   -targets=host-triple,openmp-triple1,openmp-triple2
5794   //   -outputs=input_file
5795   //   -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5796 
5797   ArgStringList CmdArgs;
5798 
5799   // Get the type.
5800   CmdArgs.push_back(TCArgs.MakeArgString(
5801       Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5802 
5803   assert(JA.getInputs().size() == Inputs.size() &&
5804          "Not have inputs for all dependence actions??");
5805 
5806   // Get the targets.
5807   SmallString<128> Triples;
5808   Triples += "-targets=";
5809   for (unsigned I = 0; I < Inputs.size(); ++I) {
5810     if (I)
5811       Triples += ',';
5812 
5813     // Find ToolChain for this input.
5814     Action::OffloadKind CurKind = Action::OFK_Host;
5815     const ToolChain *CurTC = &getToolChain();
5816     const Action *CurDep = JA.getInputs()[I];
5817 
5818     if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
5819       CurTC = nullptr;
5820       OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
5821         assert(CurTC == nullptr && "Expected one dependence!");
5822         CurKind = A->getOffloadingDeviceKind();
5823         CurTC = TC;
5824       });
5825     }
5826     Triples += Action::GetOffloadKindName(CurKind);
5827     Triples += '-';
5828     Triples += CurTC->getTriple().normalize();
5829     if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
5830       Triples += '-';
5831       Triples += CurDep->getOffloadingArch();
5832     }
5833   }
5834   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5835 
5836   // Get bundled file command.
5837   CmdArgs.push_back(
5838       TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5839 
5840   // Get unbundled files command.
5841   SmallString<128> UB;
5842   UB += "-inputs=";
5843   for (unsigned I = 0; I < Inputs.size(); ++I) {
5844     if (I)
5845       UB += ',';
5846 
5847     // Find ToolChain for this input.
5848     const ToolChain *CurTC = &getToolChain();
5849     if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
5850       CurTC = nullptr;
5851       OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
5852         assert(CurTC == nullptr && "Expected one dependence!");
5853         CurTC = TC;
5854       });
5855     }
5856     UB += CurTC->getInputFilename(Inputs[I]);
5857   }
5858   CmdArgs.push_back(TCArgs.MakeArgString(UB));
5859 
5860   // All the inputs are encoded as commands.
5861   C.addCommand(llvm::make_unique<Command>(
5862       JA, *this,
5863       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5864       CmdArgs, None));
5865 }
5866 
5867 void OffloadBundler::ConstructJobMultipleOutputs(
5868     Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5869     const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5870     const char *LinkingOutput) const {
5871   // The version with multiple outputs is expected to refer to a unbundling job.
5872   auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5873 
5874   // The unbundling command looks like this:
5875   // clang-offload-bundler -type=bc
5876   //   -targets=host-triple,openmp-triple1,openmp-triple2
5877   //   -inputs=input_file
5878   //   -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5879   //   -unbundle
5880 
5881   ArgStringList CmdArgs;
5882 
5883   assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5884   InputInfo Input = Inputs.front();
5885 
5886   // Get the type.
5887   CmdArgs.push_back(TCArgs.MakeArgString(
5888       Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5889 
5890   // Get the targets.
5891   SmallString<128> Triples;
5892   Triples += "-targets=";
5893   auto DepInfo = UA.getDependentActionsInfo();
5894   for (unsigned I = 0; I < DepInfo.size(); ++I) {
5895     if (I)
5896       Triples += ',';
5897 
5898     auto &Dep = DepInfo[I];
5899     Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5900     Triples += '-';
5901     Triples += Dep.DependentToolChain->getTriple().normalize();
5902     if (Dep.DependentOffloadKind == Action::OFK_HIP &&
5903         !Dep.DependentBoundArch.empty()) {
5904       Triples += '-';
5905       Triples += Dep.DependentBoundArch;
5906     }
5907   }
5908 
5909   CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5910 
5911   // Get bundled file command.
5912   CmdArgs.push_back(
5913       TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5914 
5915   // Get unbundled files command.
5916   SmallString<128> UB;
5917   UB += "-outputs=";
5918   for (unsigned I = 0; I < Outputs.size(); ++I) {
5919     if (I)
5920       UB += ',';
5921     UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
5922   }
5923   CmdArgs.push_back(TCArgs.MakeArgString(UB));
5924   CmdArgs.push_back("-unbundle");
5925 
5926   // All the inputs are encoded as commands.
5927   C.addCommand(llvm::make_unique<Command>(
5928       JA, *this,
5929       TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5930       CmdArgs, None));
5931 }
5932