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