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