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