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