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