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