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