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