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