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