clang  15.0.0git
CompilerInvocation.cpp
Go to the documentation of this file.
1 //===- CompilerInvocation.cpp ---------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
11 #include "clang/Basic/Builtins.h"
12 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Basic/LLVM.h"
24 #include "clang/Basic/Sanitizers.h"
27 #include "clang/Basic/Version.h"
28 #include "clang/Basic/Visibility.h"
29 #include "clang/Basic/XRayInstr.h"
30 #include "clang/Config/config.h"
31 #include "clang/Driver/Driver.h"
33 #include "clang/Driver/Options.h"
42 #include "clang/Frontend/Utils.h"
49 #include "llvm/ADT/APInt.h"
50 #include "llvm/ADT/ArrayRef.h"
51 #include "llvm/ADT/CachedHashString.h"
52 #include "llvm/ADT/DenseSet.h"
53 #include "llvm/ADT/FloatingPointMode.h"
54 #include "llvm/ADT/Hashing.h"
55 #include "llvm/ADT/None.h"
56 #include "llvm/ADT/Optional.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallString.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/StringRef.h"
61 #include "llvm/ADT/StringSwitch.h"
62 #include "llvm/ADT/Triple.h"
63 #include "llvm/ADT/Twine.h"
64 #include "llvm/Config/llvm-config.h"
65 #include "llvm/IR/DebugInfoMetadata.h"
66 #include "llvm/Linker/Linker.h"
67 #include "llvm/MC/MCTargetOptions.h"
68 #include "llvm/Option/Arg.h"
69 #include "llvm/Option/ArgList.h"
70 #include "llvm/Option/OptSpecifier.h"
71 #include "llvm/Option/OptTable.h"
72 #include "llvm/Option/Option.h"
73 #include "llvm/ProfileData/InstrProfReader.h"
74 #include "llvm/Remarks/HotnessThresholdParser.h"
75 #include "llvm/Support/CodeGen.h"
76 #include "llvm/Support/Compiler.h"
77 #include "llvm/Support/Error.h"
78 #include "llvm/Support/ErrorHandling.h"
79 #include "llvm/Support/ErrorOr.h"
80 #include "llvm/Support/FileSystem.h"
81 #include "llvm/Support/HashBuilder.h"
82 #include "llvm/Support/Host.h"
83 #include "llvm/Support/MathExtras.h"
84 #include "llvm/Support/MemoryBuffer.h"
85 #include "llvm/Support/Path.h"
86 #include "llvm/Support/Process.h"
87 #include "llvm/Support/Regex.h"
88 #include "llvm/Support/VersionTuple.h"
89 #include "llvm/Support/VirtualFileSystem.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include "llvm/Target/TargetOptions.h"
92 #include <algorithm>
93 #include <atomic>
94 #include <cassert>
95 #include <cstddef>
96 #include <cstring>
97 #include <fstream>
98 #include <memory>
99 #include <string>
100 #include <tuple>
101 #include <type_traits>
102 #include <utility>
103 #include <vector>
104 
105 using namespace clang;
106 using namespace driver;
107 using namespace options;
108 using namespace llvm::opt;
109 
110 //===----------------------------------------------------------------------===//
111 // Helpers.
112 //===----------------------------------------------------------------------===//
113 
114 // Parse misexpect tolerance argument value.
115 // Valid option values are integers in the range [0, 100)
117  int64_t Val;
118  if (Arg.getAsInteger(10, Val))
119  return llvm::createStringError(llvm::inconvertibleErrorCode(),
120  "Not an integer: %s", Arg.data());
121  return Val;
122 }
123 
124 //===----------------------------------------------------------------------===//
125 // Initialization.
126 //===----------------------------------------------------------------------===//
127 
129  : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
130  DiagnosticOpts(new DiagnosticOptions()),
131  HeaderSearchOpts(new HeaderSearchOptions()),
132  PreprocessorOpts(new PreprocessorOptions()),
133  AnalyzerOpts(new AnalyzerOptions()) {}
134 
137  : LangOpts(new LangOptions(*X.getLangOpts())),
138  TargetOpts(new TargetOptions(X.getTargetOpts())),
139  DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
140  HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
141  PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())),
142  AnalyzerOpts(new AnalyzerOptions(*X.getAnalyzerOpts())) {}
143 
145  CompilerInvocationRefBase &&X) = default;
146 
149  LangOpts.swap(X.LangOpts);
150  TargetOpts.swap(X.TargetOpts);
151  DiagnosticOpts.swap(X.DiagnosticOpts);
152  HeaderSearchOpts.swap(X.HeaderSearchOpts);
153  PreprocessorOpts.swap(X.PreprocessorOpts);
154  AnalyzerOpts.swap(X.AnalyzerOpts);
155  return *this;
156 }
157 
160 
162 
163 //===----------------------------------------------------------------------===//
164 // Normalizers
165 //===----------------------------------------------------------------------===//
166 
167 #define SIMPLE_ENUM_VALUE_TABLE
168 #include "clang/Driver/Options.inc"
169 #undef SIMPLE_ENUM_VALUE_TABLE
170 
172  unsigned TableIndex,
173  const ArgList &Args,
174  DiagnosticsEngine &Diags) {
175  if (Args.hasArg(Opt))
176  return true;
177  return None;
178 }
179 
180 static Optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned,
181  const ArgList &Args,
182  DiagnosticsEngine &) {
183  if (Args.hasArg(Opt))
184  return false;
185  return None;
186 }
187 
188 /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
189 /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
190 /// unnecessary template instantiations and just ignore it with a variadic
191 /// argument.
193  const char *Spelling,
195  Option::OptionClass, unsigned, /*T*/...) {
196  Args.push_back(Spelling);
197 }
198 
199 template <typename T> static constexpr bool is_uint64_t_convertible() {
200  return !std::is_same<T, uint64_t>::value &&
201  llvm::is_integral_or_enum<T>::value;
202 }
203 
204 template <typename T,
205  std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
207  return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
209  if (Args.hasArg(Opt))
210  return Value;
211  return None;
212  };
213 }
214 
215 template <typename T,
216  std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
217 static auto makeFlagToValueNormalizer(T Value) {
219 }
220 
221 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
222  OptSpecifier OtherOpt) {
223  return [Value, OtherValue, OtherOpt](OptSpecifier Opt, unsigned,
224  const ArgList &Args,
226  if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
227  return A->getOption().matches(Opt) ? Value : OtherValue;
228  }
229  return None;
230  };
231 }
232 
234  return [Value](SmallVectorImpl<const char *> &Args, const char *Spelling,
235  CompilerInvocation::StringAllocator, Option::OptionClass,
236  unsigned, bool KeyPath) {
237  if (KeyPath == Value)
238  Args.push_back(Spelling);
239  };
240 }
241 
243  const char *Spelling,
245  Option::OptionClass OptClass, unsigned,
246  const Twine &Value) {
247  switch (OptClass) {
248  case Option::SeparateClass:
249  case Option::JoinedOrSeparateClass:
250  case Option::JoinedAndSeparateClass:
251  Args.push_back(Spelling);
252  Args.push_back(SA(Value));
253  break;
254  case Option::JoinedClass:
255  case Option::CommaJoinedClass:
256  Args.push_back(SA(Twine(Spelling) + Value));
257  break;
258  default:
259  llvm_unreachable("Cannot denormalize an option with option class "
260  "incompatible with string denormalization.");
261  }
262 }
263 
264 template <typename T>
265 static void
268  Option::OptionClass OptClass, unsigned TableIndex, T Value) {
269  denormalizeStringImpl(Args, Spelling, SA, OptClass, TableIndex, Twine(Value));
270 }
271 
273 findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
274  for (int I = 0, E = Table.Size; I != E; ++I)
275  if (Name == Table.Table[I].Name)
276  return Table.Table[I];
277 
278  return None;
279 }
280 
282 findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
283  for (int I = 0, E = Table.Size; I != E; ++I)
284  if (Value == Table.Table[I].Value)
285  return Table.Table[I];
286 
287  return None;
288 }
289 
291  unsigned TableIndex,
292  const ArgList &Args,
293  DiagnosticsEngine &Diags) {
294  assert(TableIndex < SimpleEnumValueTablesSize);
295  const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
296 
297  auto *Arg = Args.getLastArg(Opt);
298  if (!Arg)
299  return None;
300 
301  StringRef ArgValue = Arg->getValue();
302  if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
303  return MaybeEnumVal->Value;
304 
305  Diags.Report(diag::err_drv_invalid_value)
306  << Arg->getAsString(Args) << ArgValue;
307  return None;
308 }
309 
311  const char *Spelling,
313  Option::OptionClass OptClass,
314  unsigned TableIndex, unsigned Value) {
315  assert(TableIndex < SimpleEnumValueTablesSize);
316  const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
317  if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
318  denormalizeString(Args, Spelling, SA, OptClass, TableIndex,
319  MaybeEnumVal->Name);
320  } else {
321  llvm_unreachable("The simple enum value was not correctly defined in "
322  "the tablegen option description");
323  }
324 }
325 
326 template <typename T>
328  const char *Spelling,
330  Option::OptionClass OptClass,
331  unsigned TableIndex, T Value) {
332  return denormalizeSimpleEnumImpl(Args, Spelling, SA, OptClass, TableIndex,
333  static_cast<unsigned>(Value));
334 }
335 
336 static Optional<std::string> normalizeString(OptSpecifier Opt, int TableIndex,
337  const ArgList &Args,
338  DiagnosticsEngine &Diags) {
339  auto *Arg = Args.getLastArg(Opt);
340  if (!Arg)
341  return None;
342  return std::string(Arg->getValue());
343 }
344 
345 template <typename IntTy>
346 static Optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
347  const ArgList &Args,
348  DiagnosticsEngine &Diags) {
349  auto *Arg = Args.getLastArg(Opt);
350  if (!Arg)
351  return None;
352  IntTy Res;
353  if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
354  Diags.Report(diag::err_drv_invalid_int_value)
355  << Arg->getAsString(Args) << Arg->getValue();
356  return None;
357  }
358  return Res;
359 }
360 
362 normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
363  DiagnosticsEngine &) {
364  return Args.getAllArgValues(Opt);
365 }
366 
368  const char *Spelling,
370  Option::OptionClass OptClass,
371  unsigned TableIndex,
372  const std::vector<std::string> &Values) {
373  switch (OptClass) {
374  case Option::CommaJoinedClass: {
375  std::string CommaJoinedValue;
376  if (!Values.empty()) {
377  CommaJoinedValue.append(Values.front());
378  for (const std::string &Value : llvm::drop_begin(Values, 1)) {
379  CommaJoinedValue.append(",");
380  CommaJoinedValue.append(Value);
381  }
382  }
383  denormalizeString(Args, Spelling, SA, Option::OptionClass::JoinedClass,
384  TableIndex, CommaJoinedValue);
385  break;
386  }
387  case Option::JoinedClass:
388  case Option::SeparateClass:
389  case Option::JoinedOrSeparateClass:
390  for (const std::string &Value : Values)
391  denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
392  break;
393  default:
394  llvm_unreachable("Cannot denormalize an option with option class "
395  "incompatible with string vector denormalization.");
396  }
397 }
398 
399 static Optional<std::string> normalizeTriple(OptSpecifier Opt, int TableIndex,
400  const ArgList &Args,
401  DiagnosticsEngine &Diags) {
402  auto *Arg = Args.getLastArg(Opt);
403  if (!Arg)
404  return None;
405  return llvm::Triple::normalize(Arg->getValue());
406 }
407 
408 template <typename T, typename U>
409 static T mergeForwardValue(T KeyPath, U Value) {
410  return static_cast<T>(Value);
411 }
412 
413 template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
414  return KeyPath | Value;
415 }
416 
417 template <typename T> static T extractForwardValue(T KeyPath) {
418  return KeyPath;
419 }
420 
421 template <typename T, typename U, U Value>
422 static T extractMaskValue(T KeyPath) {
423  return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T();
424 }
425 
426 #define PARSE_OPTION_WITH_MARSHALLING( \
427  ARGS, DIAGS, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
428  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX) \
429  if ((FLAGS)&options::CC1Option) { \
430  KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \
431  if (IMPLIED_CHECK) \
432  KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \
433  if (SHOULD_PARSE) \
434  if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \
435  KEYPATH = \
436  MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \
437  }
438 
439 // Capture the extracted value as a lambda argument to avoid potential issues
440 // with lifetime extension of the reference.
441 #define GENERATE_OPTION_WITH_MARSHALLING( \
442  ARGS, STRING_ALLOCATOR, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, \
443  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, \
444  TABLE_INDEX) \
445  if ((FLAGS)&options::CC1Option) { \
446  [&](const auto &Extracted) { \
447  if (ALWAYS_EMIT || \
448  (Extracted != \
449  static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \
450  : (DEFAULT_VALUE)))) \
451  DENORMALIZER(ARGS, SPELLING, STRING_ALLOCATOR, Option::KIND##Class, \
452  TABLE_INDEX, Extracted); \
453  }(EXTRACTOR(KEYPATH)); \
454  }
455 
456 static StringRef GetInputKindName(InputKind IK);
457 
458 static bool FixupInvocation(CompilerInvocation &Invocation,
459  DiagnosticsEngine &Diags, const ArgList &Args,
460  InputKind IK) {
461  unsigned NumErrorsBefore = Diags.getNumErrors();
462 
463  LangOptions &LangOpts = *Invocation.getLangOpts();
464  CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
465  TargetOptions &TargetOpts = Invocation.getTargetOpts();
466  FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
467  CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
468  CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
469  CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
470  CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
471  FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
472  if (FrontendOpts.ShowStats)
473  CodeGenOpts.ClearASTBeforeBackend = false;
474  LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
475  LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
476  LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
477  LangOpts.CurrentModule = LangOpts.ModuleName;
478 
479  llvm::Triple T(TargetOpts.Triple);
480  llvm::Triple::ArchType Arch = T.getArch();
481 
482  CodeGenOpts.CodeModel = TargetOpts.CodeModel;
483 
484  if (LangOpts.getExceptionHandling() !=
486  T.isWindowsMSVCEnvironment())
487  Diags.Report(diag::err_fe_invalid_exception_model)
488  << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
489 
490  if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
491  Diags.Report(diag::warn_c_kext);
492 
493  if (Args.hasArg(OPT_fconcepts_ts))
494  Diags.Report(diag::warn_fe_concepts_ts_flag);
495 
496  if (LangOpts.NewAlignOverride &&
497  !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
498  Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
499  Diags.Report(diag::err_fe_invalid_alignment)
500  << A->getAsString(Args) << A->getValue();
501  LangOpts.NewAlignOverride = 0;
502  }
503 
504  // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
505  if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
506  Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
507  << "-fsycl-is-host";
508 
509  if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
510  Diags.Report(diag::err_drv_argument_not_allowed_with)
511  << "-fgnu89-inline" << GetInputKindName(IK);
512 
513  if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
514  Diags.Report(diag::warn_ignored_hip_only_option)
515  << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
516 
517  if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
518  Diags.Report(diag::warn_ignored_hip_only_option)
519  << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
520 
521  // When these options are used, the compiler is allowed to apply
522  // optimizations that may affect the final result. For example
523  // (x+y)+z is transformed to x+(y+z) but may not give the same
524  // final result; it's not value safe.
525  // Another example can be to simplify x/x to 1.0 but x could be 0.0, INF
526  // or NaN. Final result may then differ. An error is issued when the eval
527  // method is set with one of these options.
528  if (Args.hasArg(OPT_ffp_eval_method_EQ)) {
529  if (LangOpts.ApproxFunc)
530  Diags.Report(diag::err_incompatible_fp_eval_method_options) << 0;
531  if (LangOpts.AllowFPReassoc)
532  Diags.Report(diag::err_incompatible_fp_eval_method_options) << 1;
533  if (LangOpts.AllowRecip)
534  Diags.Report(diag::err_incompatible_fp_eval_method_options) << 2;
535  }
536 
537  // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
538  // This option should be deprecated for CL > 1.0 because
539  // this option was added for compatibility with OpenCL 1.0.
540  if (Args.getLastArg(OPT_cl_strict_aliasing) &&
541  (LangOpts.getOpenCLCompatibleVersion() > 100))
542  Diags.Report(diag::warn_option_invalid_ocl_version)
543  << LangOpts.getOpenCLVersionString()
544  << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
545 
546  if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
547  auto DefaultCC = LangOpts.getDefaultCallingConv();
548 
549  bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
550  DefaultCC == LangOptions::DCC_StdCall) &&
551  Arch != llvm::Triple::x86;
552  emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
553  DefaultCC == LangOptions::DCC_RegCall) &&
554  !T.isX86();
555  if (emitError)
556  Diags.Report(diag::err_drv_argument_not_allowed_with)
557  << A->getSpelling() << T.getTriple();
558  }
559 
560  return Diags.getNumErrors() == NumErrorsBefore;
561 }
562 
563 //===----------------------------------------------------------------------===//
564 // Deserialization (from args)
565 //===----------------------------------------------------------------------===//
566 
567 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
568  DiagnosticsEngine &Diags) {
569  unsigned DefaultOpt = llvm::CodeGenOpt::None;
570  if ((IK.getLanguage() == Language::OpenCL ||
571  IK.getLanguage() == Language::OpenCLCXX) &&
572  !Args.hasArg(OPT_cl_opt_disable))
573  DefaultOpt = llvm::CodeGenOpt::Default;
574 
575  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
576  if (A->getOption().matches(options::OPT_O0))
577  return llvm::CodeGenOpt::None;
578 
579  if (A->getOption().matches(options::OPT_Ofast))
580  return llvm::CodeGenOpt::Aggressive;
581 
582  assert(A->getOption().matches(options::OPT_O));
583 
584  StringRef S(A->getValue());
585  if (S == "s" || S == "z")
586  return llvm::CodeGenOpt::Default;
587 
588  if (S == "g")
589  return llvm::CodeGenOpt::Less;
590 
591  return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
592  }
593 
594  return DefaultOpt;
595 }
596 
597 static unsigned getOptimizationLevelSize(ArgList &Args) {
598  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
599  if (A->getOption().matches(options::OPT_O)) {
600  switch (A->getValue()[0]) {
601  default:
602  return 0;
603  case 's':
604  return 1;
605  case 'z':
606  return 2;
607  }
608  }
609  }
610  return 0;
611 }
612 
614  llvm::opt::OptSpecifier OptSpecifier,
616  Option Opt = getDriverOptTable().getOption(OptSpecifier);
617  denormalizeSimpleFlag(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
618  Option::OptionClass::FlagClass, 0);
619 }
620 
622  llvm::opt::OptSpecifier OptSpecifier,
623  const Twine &Value,
625  Option Opt = getDriverOptTable().getOption(OptSpecifier);
626  denormalizeString(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
627  Opt.getKind(), 0, Value);
628 }
629 
630 // Parse command line arguments into CompilerInvocation.
631 using ParseFn =
632  llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
633  DiagnosticsEngine &, const char *)>;
634 
635 // Generate command line arguments from CompilerInvocation.
636 using GenerateFn = llvm::function_ref<void(
639 
640 // May perform round-trip of command line arguments. By default, the round-trip
641 // is enabled in assert builds. This can be overwritten at run-time via the
642 // "-round-trip-args" and "-no-round-trip-args" command line flags.
643 // During round-trip, the command line arguments are parsed into a dummy
644 // instance of CompilerInvocation which is used to generate the command line
645 // arguments again. The real CompilerInvocation instance is then created by
646 // parsing the generated arguments, not the original ones.
647 static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
648  CompilerInvocation &RealInvocation,
649  CompilerInvocation &DummyInvocation,
650  ArrayRef<const char *> CommandLineArgs,
651  DiagnosticsEngine &Diags, const char *Argv0) {
652 #ifndef NDEBUG
653  bool DoRoundTripDefault = true;
654 #else
655  bool DoRoundTripDefault = false;
656 #endif
657 
658  bool DoRoundTrip = DoRoundTripDefault;
659  for (const auto *Arg : CommandLineArgs) {
660  if (Arg == StringRef("-round-trip-args"))
661  DoRoundTrip = true;
662  if (Arg == StringRef("-no-round-trip-args"))
663  DoRoundTrip = false;
664  }
665 
666  // If round-trip was not requested, simply run the parser with the real
667  // invocation diagnostics.
668  if (!DoRoundTrip)
669  return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
670 
671  // Serializes quoted (and potentially escaped) arguments.
672  auto SerializeArgs = [](ArrayRef<const char *> Args) {
673  std::string Buffer;
674  llvm::raw_string_ostream OS(Buffer);
675  for (const char *Arg : Args) {
676  llvm::sys::printArg(OS, Arg, /*Quote=*/true);
677  OS << ' ';
678  }
679  OS.flush();
680  return Buffer;
681  };
682 
683  // Setup a dummy DiagnosticsEngine.
684  DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
685  DummyDiags.setClient(new TextDiagnosticBuffer());
686 
687  // Run the first parse on the original arguments with the dummy invocation and
688  // diagnostics.
689  if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
690  DummyDiags.getNumWarnings() != 0) {
691  // If the first parse did not succeed, it must be user mistake (invalid
692  // command line arguments). We won't be able to generate arguments that
693  // would reproduce the same result. Let's fail again with the real
694  // invocation and diagnostics, so all side-effects of parsing are visible.
695  unsigned NumWarningsBefore = Diags.getNumWarnings();
696  auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
697  if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
698  return Success;
699 
700  // Parse with original options and diagnostics succeeded even though it
701  // shouldn't have. Something is off.
702  Diags.Report(diag::err_cc1_round_trip_fail_then_ok);
703  Diags.Report(diag::note_cc1_round_trip_original)
704  << SerializeArgs(CommandLineArgs);
705  return false;
706  }
707 
708  // Setup string allocator.
709  llvm::BumpPtrAllocator Alloc;
710  llvm::StringSaver StringPool(Alloc);
711  auto SA = [&StringPool](const Twine &Arg) {
712  return StringPool.save(Arg).data();
713  };
714 
715  // Generate arguments from the dummy invocation. If Generate is the
716  // inverse of Parse, the newly generated arguments must have the same
717  // semantics as the original.
718  SmallVector<const char *> GeneratedArgs1;
719  Generate(DummyInvocation, GeneratedArgs1, SA);
720 
721  // Run the second parse, now on the generated arguments, and with the real
722  // invocation and diagnostics. The result is what we will end up using for the
723  // rest of compilation, so if Generate is not inverse of Parse, something down
724  // the line will break.
725  bool Success2 = Parse(RealInvocation, GeneratedArgs1, Diags, Argv0);
726 
727  // The first parse on original arguments succeeded, but second parse of
728  // generated arguments failed. Something must be wrong with the generator.
729  if (!Success2) {
730  Diags.Report(diag::err_cc1_round_trip_ok_then_fail);
731  Diags.Report(diag::note_cc1_round_trip_generated)
732  << 1 << SerializeArgs(GeneratedArgs1);
733  return false;
734  }
735 
736  // Generate arguments again, this time from the options we will end up using
737  // for the rest of the compilation.
738  SmallVector<const char *> GeneratedArgs2;
739  Generate(RealInvocation, GeneratedArgs2, SA);
740 
741  // Compares two lists of generated arguments.
742  auto Equal = [](const ArrayRef<const char *> A,
743  const ArrayRef<const char *> B) {
744  return std::equal(A.begin(), A.end(), B.begin(), B.end(),
745  [](const char *AElem, const char *BElem) {
746  return StringRef(AElem) == StringRef(BElem);
747  });
748  };
749 
750  // If we generated different arguments from what we assume are two
751  // semantically equivalent CompilerInvocations, the Generate function may
752  // be non-deterministic.
753  if (!Equal(GeneratedArgs1, GeneratedArgs2)) {
754  Diags.Report(diag::err_cc1_round_trip_mismatch);
755  Diags.Report(diag::note_cc1_round_trip_generated)
756  << 1 << SerializeArgs(GeneratedArgs1);
757  Diags.Report(diag::note_cc1_round_trip_generated)
758  << 2 << SerializeArgs(GeneratedArgs2);
759  return false;
760  }
761 
762  Diags.Report(diag::remark_cc1_round_trip_generated)
763  << 1 << SerializeArgs(GeneratedArgs1);
764  Diags.Report(diag::remark_cc1_round_trip_generated)
765  << 2 << SerializeArgs(GeneratedArgs2);
766 
767  return Success2;
768 }
769 
770 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
771  OptSpecifier GroupWithValue,
772  std::vector<std::string> &Diagnostics) {
773  for (auto *A : Args.filtered(Group)) {
774  if (A->getOption().getKind() == Option::FlagClass) {
775  // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
776  // its name (minus the "W" or "R" at the beginning) to the diagnostics.
777  Diagnostics.push_back(
778  std::string(A->getOption().getName().drop_front(1)));
779  } else if (A->getOption().matches(GroupWithValue)) {
780  // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
781  // group. Add only the group name to the diagnostics.
782  Diagnostics.push_back(
783  std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
784  } else {
785  // Otherwise, add its value (for OPT_W_Joined and similar).
786  Diagnostics.push_back(A->getValue());
787  }
788  }
789 }
790 
791 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
792 // it won't verify the input.
793 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
794  DiagnosticsEngine *Diags);
795 
796 static void getAllNoBuiltinFuncValues(ArgList &Args,
797  std::vector<std::string> &Funcs) {
798  std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
799  auto BuiltinEnd = llvm::partition(Values, Builtin::Context::isBuiltinFunc);
800  Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
801 }
802 
806  const AnalyzerOptions *AnalyzerOpts = &Opts;
807 
808 #define ANALYZER_OPTION_WITH_MARSHALLING( \
809  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
810  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
811  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
812  MERGER, EXTRACTOR, TABLE_INDEX) \
813  GENERATE_OPTION_WITH_MARSHALLING( \
814  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
815  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
816 #include "clang/Driver/Options.inc"
817 #undef ANALYZER_OPTION_WITH_MARSHALLING
818 
819  if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
820  switch (Opts.AnalysisConstraintsOpt) {
821 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
822  case NAME##Model: \
823  GenerateArg(Args, OPT_analyzer_constraints, CMDFLAG, SA); \
824  break;
825 #include "clang/StaticAnalyzer/Core/Analyses.def"
826  default:
827  llvm_unreachable("Tried to generate unknown analysis constraint.");
828  }
829  }
830 
831  if (Opts.AnalysisDiagOpt != PD_HTML) {
832  switch (Opts.AnalysisDiagOpt) {
833 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
834  case PD_##NAME: \
835  GenerateArg(Args, OPT_analyzer_output, CMDFLAG, SA); \
836  break;
837 #include "clang/StaticAnalyzer/Core/Analyses.def"
838  default:
839  llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
840  }
841  }
842 
843  if (Opts.AnalysisPurgeOpt != PurgeStmt) {
844  switch (Opts.AnalysisPurgeOpt) {
845 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
846  case NAME: \
847  GenerateArg(Args, OPT_analyzer_purge, CMDFLAG, SA); \
848  break;
849 #include "clang/StaticAnalyzer/Core/Analyses.def"
850  default:
851  llvm_unreachable("Tried to generate unknown analysis purge mode.");
852  }
853  }
854 
855  if (Opts.InliningMode != NoRedundancy) {
856  switch (Opts.InliningMode) {
857 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
858  case NAME: \
859  GenerateArg(Args, OPT_analyzer_inlining_mode, CMDFLAG, SA); \
860  break;
861 #include "clang/StaticAnalyzer/Core/Analyses.def"
862  default:
863  llvm_unreachable("Tried to generate unknown analysis inlining mode.");
864  }
865  }
866 
867  for (const auto &CP : Opts.CheckersAndPackages) {
868  OptSpecifier Opt =
869  CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
870  GenerateArg(Args, Opt, CP.first, SA);
871  }
872 
873  AnalyzerOptions ConfigOpts;
874  parseAnalyzerConfigs(ConfigOpts, nullptr);
875 
876  for (const auto &C : Opts.Config) {
877  // Don't generate anything that came from parseAnalyzerConfigs. It would be
878  // redundant and may not be valid on the command line.
879  auto Entry = ConfigOpts.Config.find(C.getKey());
880  if (Entry != ConfigOpts.Config.end() && Entry->getValue() == C.getValue())
881  continue;
882 
883  GenerateArg(Args, OPT_analyzer_config, C.getKey() + "=" + C.getValue(), SA);
884  }
885 
886  // Nothing to generate for FullCompilerInvocation.
887 }
888 
889 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
890  DiagnosticsEngine &Diags) {
891  unsigned NumErrorsBefore = Diags.getNumErrors();
892 
893  AnalyzerOptions *AnalyzerOpts = &Opts;
894 
895 #define ANALYZER_OPTION_WITH_MARSHALLING( \
896  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
897  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
898  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
899  MERGER, EXTRACTOR, TABLE_INDEX) \
900  PARSE_OPTION_WITH_MARSHALLING( \
901  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
902  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
903 #include "clang/Driver/Options.inc"
904 #undef ANALYZER_OPTION_WITH_MARSHALLING
905 
906  if (Args.hasArg(OPT_analyzer_store))
907  Diags.Report(diag::warn_analyzer_deprecated_option) << "-analyzer-store"
908  << "clang-16";
909  if (Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks))
910  Diags.Report(diag::warn_analyzer_deprecated_option)
911  << "-analyzer-opt-analyze-nested-blocks"
912  << "clang-16";
913 
914  if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
915  StringRef Name = A->getValue();
916  AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
917 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
918  .Case(CMDFLAG, NAME##Model)
919 #include "clang/StaticAnalyzer/Core/Analyses.def"
920  .Default(NumConstraints);
921  if (Value == NumConstraints) {
922  Diags.Report(diag::err_drv_invalid_value)
923  << A->getAsString(Args) << Name;
924  } else {
925 #ifndef LLVM_WITH_Z3
926  if (Value == AnalysisConstraints::Z3ConstraintsModel) {
927  Diags.Report(diag::err_analyzer_not_built_with_z3);
928  }
929 #endif // LLVM_WITH_Z3
931  }
932  }
933 
934  if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
935  StringRef Name = A->getValue();
936  AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
937 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
938  .Case(CMDFLAG, PD_##NAME)
939 #include "clang/StaticAnalyzer/Core/Analyses.def"
940  .Default(NUM_ANALYSIS_DIAG_CLIENTS);
942  Diags.Report(diag::err_drv_invalid_value)
943  << A->getAsString(Args) << Name;
944  } else {
945  Opts.AnalysisDiagOpt = Value;
946  }
947  }
948 
949  if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
950  StringRef Name = A->getValue();
951  AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
952 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
953  .Case(CMDFLAG, NAME)
954 #include "clang/StaticAnalyzer/Core/Analyses.def"
955  .Default(NumPurgeModes);
956  if (Value == NumPurgeModes) {
957  Diags.Report(diag::err_drv_invalid_value)
958  << A->getAsString(Args) << Name;
959  } else {
960  Opts.AnalysisPurgeOpt = Value;
961  }
962  }
963 
964  if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
965  StringRef Name = A->getValue();
966  AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
967 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
968  .Case(CMDFLAG, NAME)
969 #include "clang/StaticAnalyzer/Core/Analyses.def"
970  .Default(NumInliningModes);
971  if (Value == NumInliningModes) {
972  Diags.Report(diag::err_drv_invalid_value)
973  << A->getAsString(Args) << Name;
974  } else {
975  Opts.InliningMode = Value;
976  }
977  }
978 
979  Opts.CheckersAndPackages.clear();
980  for (const Arg *A :
981  Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
982  A->claim();
983  bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
984  // We can have a list of comma separated checker names, e.g:
985  // '-analyzer-checker=cocoa,unix'
986  StringRef CheckerAndPackageList = A->getValue();
987  SmallVector<StringRef, 16> CheckersAndPackages;
988  CheckerAndPackageList.split(CheckersAndPackages, ",");
989  for (const StringRef &CheckerOrPackage : CheckersAndPackages)
990  Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
991  IsEnabled);
992  }
993 
994  // Go through the analyzer configuration options.
995  for (const auto *A : Args.filtered(OPT_analyzer_config)) {
996 
997  // We can have a list of comma separated config names, e.g:
998  // '-analyzer-config key1=val1,key2=val2'
999  StringRef configList = A->getValue();
1000  SmallVector<StringRef, 4> configVals;
1001  configList.split(configVals, ",");
1002  for (const auto &configVal : configVals) {
1003  StringRef key, val;
1004  std::tie(key, val) = configVal.split("=");
1005  if (val.empty()) {
1006  Diags.Report(SourceLocation(),
1007  diag::err_analyzer_config_no_value) << configVal;
1008  break;
1009  }
1010  if (val.contains('=')) {
1011  Diags.Report(SourceLocation(),
1012  diag::err_analyzer_config_multiple_values)
1013  << configVal;
1014  break;
1015  }
1016 
1017  // TODO: Check checker options too, possibly in CheckerRegistry.
1018  // Leave unknown non-checker configs unclaimed.
1019  if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
1021  Diags.Report(diag::err_analyzer_config_unknown) << key;
1022  continue;
1023  }
1024 
1025  A->claim();
1026  Opts.Config[key] = std::string(val);
1027  }
1028  }
1029 
1031  parseAnalyzerConfigs(Opts, &Diags);
1032  else
1033  parseAnalyzerConfigs(Opts, nullptr);
1034 
1035  llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
1036  for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
1037  if (i != 0)
1038  os << " ";
1039  os << Args.getArgString(i);
1040  }
1041  os.flush();
1042 
1043  return Diags.getNumErrors() == NumErrorsBefore;
1044 }
1045 
1047  StringRef OptionName, StringRef DefaultVal) {
1048  return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
1049 }
1050 
1052  DiagnosticsEngine *Diags,
1053  StringRef &OptionField, StringRef Name,
1054  StringRef DefaultVal) {
1055  // String options may be known to invalid (e.g. if the expected string is a
1056  // file name, but the file does not exist), those will have to be checked in
1057  // parseConfigs.
1058  OptionField = getStringOption(Config, Name, DefaultVal);
1059 }
1060 
1062  DiagnosticsEngine *Diags,
1063  bool &OptionField, StringRef Name, bool DefaultVal) {
1064  auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>(
1065  getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
1066  .Case("true", true)
1067  .Case("false", false)
1068  .Default(None);
1069 
1070  if (!PossiblyInvalidVal) {
1071  if (Diags)
1072  Diags->Report(diag::err_analyzer_config_invalid_input)
1073  << Name << "a boolean";
1074  else
1075  OptionField = DefaultVal;
1076  } else
1077  OptionField = *PossiblyInvalidVal;
1078 }
1079 
1081  DiagnosticsEngine *Diags,
1082  unsigned &OptionField, StringRef Name,
1083  unsigned DefaultVal) {
1084 
1085  OptionField = DefaultVal;
1086  bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
1087  .getAsInteger(0, OptionField);
1088  if (Diags && HasFailed)
1089  Diags->Report(diag::err_analyzer_config_invalid_input)
1090  << Name << "an unsigned";
1091 }
1092 
1094  DiagnosticsEngine *Diags) {
1095  // TODO: There's no need to store the entire configtable, it'd be plenty
1096  // enough to store checker options.
1097 
1098 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
1099  initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
1100 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(...)
1101 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1102 
1103  assert(AnOpts.UserMode == "shallow" || AnOpts.UserMode == "deep");
1104  const bool InShallowMode = AnOpts.UserMode == "shallow";
1105 
1106 #define ANALYZER_OPTION(...)
1107 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
1108  SHALLOW_VAL, DEEP_VAL) \
1109  initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, \
1110  InShallowMode ? SHALLOW_VAL : DEEP_VAL);
1111 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1112 
1113  // At this point, AnalyzerOptions is configured. Let's validate some options.
1114 
1115  // FIXME: Here we try to validate the silenced checkers or packages are valid.
1116  // The current approach only validates the registered checkers which does not
1117  // contain the runtime enabled checkers and optimally we would validate both.
1118  if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
1119  std::vector<StringRef> Checkers =
1120  AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
1121  std::vector<StringRef> Packages =
1122  AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
1123 
1124  SmallVector<StringRef, 16> CheckersAndPackages;
1125  AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
1126 
1127  for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
1128  if (Diags) {
1129  bool IsChecker = CheckerOrPackage.contains('.');
1130  bool IsValidName = IsChecker
1131  ? llvm::is_contained(Checkers, CheckerOrPackage)
1132  : llvm::is_contained(Packages, CheckerOrPackage);
1133 
1134  if (!IsValidName)
1135  Diags->Report(diag::err_unknown_analyzer_checker_or_package)
1136  << CheckerOrPackage;
1137  }
1138 
1139  AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
1140  }
1141  }
1142 
1143  if (!Diags)
1144  return;
1145 
1146  if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
1147  Diags->Report(diag::err_analyzer_config_invalid_input)
1148  << "track-conditions-debug" << "'track-conditions' to also be enabled";
1149 
1150  if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
1151  Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
1152  << "a filename";
1153 
1154  if (!AnOpts.ModelPath.empty() &&
1155  !llvm::sys::fs::is_directory(AnOpts.ModelPath))
1156  Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
1157  << "a filename";
1158 }
1159 
1160 /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
1161 static void
1164  OptSpecifier OptEQ, StringRef Name,
1165  const CodeGenOptions::OptRemark &Remark) {
1166  if (Remark.hasValidPattern()) {
1167  GenerateArg(Args, OptEQ, Remark.Pattern, SA);
1168  } else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
1169  GenerateArg(Args, OPT_R_Joined, Name, SA);
1170  } else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
1171  GenerateArg(Args, OPT_R_Joined, StringRef("no-") + Name, SA);
1172  }
1173 }
1174 
1175 /// Parse a remark command line argument. It may be missing, disabled/enabled by
1176 /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
1177 /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
1180  OptSpecifier OptEQ, StringRef Name) {
1182 
1183  auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A,
1184  StringRef Pattern) {
1185  Result.Pattern = Pattern.str();
1186 
1187  std::string RegexError;
1188  Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
1189  if (!Result.Regex->isValid(RegexError)) {
1190  Diags.Report(diag::err_drv_optimization_remark_pattern)
1191  << RegexError << A->getAsString(Args);
1192  return false;
1193  }
1194 
1195  return true;
1196  };
1197 
1198  for (Arg *A : Args) {
1199  if (A->getOption().matches(OPT_R_Joined)) {
1200  StringRef Value = A->getValue();
1201 
1202  if (Value == Name)
1204  else if (Value == "everything")
1206  else if (Value.split('-') == std::make_pair(StringRef("no"), Name))
1208  else if (Value == "no-everything")
1210  else
1211  continue;
1212 
1213  if (Result.Kind == CodeGenOptions::RK_Disabled ||
1215  Result.Pattern = "";
1216  Result.Regex = nullptr;
1217  } else {
1218  InitializeResultPattern(A, ".*");
1219  }
1220  } else if (A->getOption().matches(OptEQ)) {
1222  if (!InitializeResultPattern(A, A->getValue()))
1223  return CodeGenOptions::OptRemark();
1224  }
1225  }
1226 
1227  return Result;
1228 }
1229 
1230 static bool parseDiagnosticLevelMask(StringRef FlagName,
1231  const std::vector<std::string> &Levels,
1232  DiagnosticsEngine &Diags,
1233  DiagnosticLevelMask &M) {
1234  bool Success = true;
1235  for (const auto &Level : Levels) {
1236  DiagnosticLevelMask const PM =
1237  llvm::StringSwitch<DiagnosticLevelMask>(Level)
1238  .Case("note", DiagnosticLevelMask::Note)
1239  .Case("remark", DiagnosticLevelMask::Remark)
1240  .Case("warning", DiagnosticLevelMask::Warning)
1241  .Case("error", DiagnosticLevelMask::Error)
1242  .Default(DiagnosticLevelMask::None);
1243  if (PM == DiagnosticLevelMask::None) {
1244  Success = false;
1245  Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
1246  }
1247  M = M | PM;
1248  }
1249  return Success;
1250 }
1251 
1252 static void parseSanitizerKinds(StringRef FlagName,
1253  const std::vector<std::string> &Sanitizers,
1254  DiagnosticsEngine &Diags, SanitizerSet &S) {
1255  for (const auto &Sanitizer : Sanitizers) {
1256  SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
1257  if (K == SanitizerMask())
1258  Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
1259  else
1260  S.set(K, true);
1261  }
1262 }
1263 
1264 static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) {
1265  SmallVector<StringRef, 4> Values;
1266  serializeSanitizerSet(S, Values);
1267  return Values;
1268 }
1269 
1270 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
1271  ArgList &Args, DiagnosticsEngine &D,
1272  XRayInstrSet &S) {
1273  llvm::SmallVector<StringRef, 2> BundleParts;
1274  llvm::SplitString(Bundle, BundleParts, ",");
1275  for (const auto &B : BundleParts) {
1276  auto Mask = parseXRayInstrValue(B);
1277  if (Mask == XRayInstrKind::None)
1278  if (B != "none")
1279  D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
1280  else
1281  S.Mask = Mask;
1282  else if (Mask == XRayInstrKind::All)
1283  S.Mask = Mask;
1284  else
1285  S.set(Mask, true);
1286  }
1287 }
1288 
1290  llvm::SmallVector<StringRef, 2> BundleParts;
1291  serializeXRayInstrValue(S, BundleParts);
1292  std::string Buffer;
1293  llvm::raw_string_ostream OS(Buffer);
1294  llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
1295  return Buffer;
1296 }
1297 
1298 // Set the profile kind using fprofile-instrument-use-path.
1300  const Twine &ProfileName) {
1301  auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
1302  // In error, return silently and let Clang PGOUse report the error message.
1303  if (auto E = ReaderOrErr.takeError()) {
1304  llvm::consumeError(std::move(E));
1305  Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
1306  return;
1307  }
1308  std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
1309  std::move(ReaderOrErr.get());
1310  if (PGOReader->isIRLevelProfile()) {
1311  if (PGOReader->hasCSIRLevelProfile())
1312  Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
1313  else
1314  Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
1315  } else
1316  Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
1317 }
1318 
1319 void CompilerInvocation::GenerateCodeGenArgs(
1320  const CodeGenOptions &Opts, SmallVectorImpl<const char *> &Args,
1321  StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile,
1322  const LangOptions *LangOpts) {
1323  const CodeGenOptions &CodeGenOpts = Opts;
1324 
1325  if (Opts.OptimizationLevel == 0)
1326  GenerateArg(Args, OPT_O0, SA);
1327  else
1328  GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
1329 
1330 #define CODEGEN_OPTION_WITH_MARSHALLING( \
1331  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
1332  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
1333  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
1334  MERGER, EXTRACTOR, TABLE_INDEX) \
1335  GENERATE_OPTION_WITH_MARSHALLING( \
1336  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
1337  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
1338 #include "clang/Driver/Options.inc"
1339 #undef CODEGEN_OPTION_WITH_MARSHALLING
1340 
1341  if (Opts.OptimizationLevel > 0) {
1342  if (Opts.Inlining == CodeGenOptions::NormalInlining)
1343  GenerateArg(Args, OPT_finline_functions, SA);
1344  else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
1345  GenerateArg(Args, OPT_finline_hint_functions, SA);
1346  else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
1347  GenerateArg(Args, OPT_fno_inline, SA);
1348  }
1349 
1350  if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
1351  GenerateArg(Args, OPT_fdirect_access_external_data, SA);
1352  else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
1353  GenerateArg(Args, OPT_fno_direct_access_external_data, SA);
1354 
1355  Optional<StringRef> DebugInfoVal;
1356  switch (Opts.DebugInfo) {
1358  DebugInfoVal = "line-tables-only";
1359  break;
1361  DebugInfoVal = "line-directives-only";
1362  break;
1364  DebugInfoVal = "limited";
1365  break;
1367  DebugInfoVal = "standalone";
1368  break;
1370  DebugInfoVal = "unused-types";
1371  break;
1372  case codegenoptions::NoDebugInfo: // default value
1373  DebugInfoVal = None;
1374  break;
1375  case codegenoptions::LocTrackingOnly: // implied value
1376  DebugInfoVal = None;
1377  break;
1378  }
1379  if (DebugInfoVal)
1380  GenerateArg(Args, OPT_debug_info_kind_EQ, *DebugInfoVal, SA);
1381 
1382  for (const auto &Prefix : Opts.DebugPrefixMap)
1383  GenerateArg(Args, OPT_fdebug_prefix_map_EQ,
1384  Prefix.first + "=" + Prefix.second, SA);
1385 
1386  for (const auto &Prefix : Opts.CoveragePrefixMap)
1387  GenerateArg(Args, OPT_fcoverage_prefix_map_EQ,
1388  Prefix.first + "=" + Prefix.second, SA);
1389 
1390  if (Opts.NewStructPathTBAA)
1391  GenerateArg(Args, OPT_new_struct_path_tbaa, SA);
1392 
1393  if (Opts.OptimizeSize == 1)
1394  GenerateArg(Args, OPT_O, "s", SA);
1395  else if (Opts.OptimizeSize == 2)
1396  GenerateArg(Args, OPT_O, "z", SA);
1397 
1398  // SimplifyLibCalls is set only in the absence of -fno-builtin and
1399  // -ffreestanding. We'll consider that when generating them.
1400 
1401  // NoBuiltinFuncs are generated by LangOptions.
1402 
1403  if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
1404  GenerateArg(Args, OPT_funroll_loops, SA);
1405  else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
1406  GenerateArg(Args, OPT_fno_unroll_loops, SA);
1407 
1408  if (!Opts.BinutilsVersion.empty())
1409  GenerateArg(Args, OPT_fbinutils_version_EQ, Opts.BinutilsVersion, SA);
1410 
1411  if (Opts.DebugNameTable ==
1412  static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
1413  GenerateArg(Args, OPT_ggnu_pubnames, SA);
1414  else if (Opts.DebugNameTable ==
1415  static_cast<unsigned>(
1416  llvm::DICompileUnit::DebugNameTableKind::Default))
1417  GenerateArg(Args, OPT_gpubnames, SA);
1418 
1419  auto TNK = Opts.getDebugSimpleTemplateNames();
1422  GenerateArg(Args, OPT_gsimple_template_names_EQ, "simple", SA);
1424  GenerateArg(Args, OPT_gsimple_template_names_EQ, "mangled", SA);
1425  }
1426  // ProfileInstrumentUsePath is marshalled automatically, no need to generate
1427  // it or PGOUseInstrumentor.
1428 
1429  if (Opts.TimePasses) {
1430  if (Opts.TimePassesPerRun)
1431  GenerateArg(Args, OPT_ftime_report_EQ, "per-pass-run", SA);
1432  else
1433  GenerateArg(Args, OPT_ftime_report, SA);
1434  }
1435 
1436  if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
1437  GenerateArg(Args, OPT_flto_EQ, "full", SA);
1438 
1439  if (Opts.PrepareForThinLTO)
1440  GenerateArg(Args, OPT_flto_EQ, "thin", SA);
1441 
1442  if (!Opts.ThinLTOIndexFile.empty())
1443  GenerateArg(Args, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile, SA);
1444 
1445  if (Opts.SaveTempsFilePrefix == OutputFile)
1446  GenerateArg(Args, OPT_save_temps_EQ, "obj", SA);
1447 
1448  StringRef MemProfileBasename("memprof.profraw");
1449  if (!Opts.MemoryProfileOutput.empty()) {
1450  if (Opts.MemoryProfileOutput == MemProfileBasename) {
1451  GenerateArg(Args, OPT_fmemory_profile, SA);
1452  } else {
1453  size_t ArgLength =
1454  Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
1455  GenerateArg(Args, OPT_fmemory_profile_EQ,
1456  Opts.MemoryProfileOutput.substr(0, ArgLength), SA);
1457  }
1458  }
1459 
1460  if (memcmp(Opts.CoverageVersion, "408*", 4) != 0)
1461  GenerateArg(Args, OPT_coverage_version_EQ,
1462  StringRef(Opts.CoverageVersion, 4), SA);
1463 
1464  // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
1465  // '-fembed_bitcode', which does not map to any CompilerInvocation field and
1466  // won't be generated.)
1467 
1469  std::string InstrBundle =
1471  if (!InstrBundle.empty())
1472  GenerateArg(Args, OPT_fxray_instrumentation_bundle, InstrBundle, SA);
1473  }
1474 
1475  if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
1476  GenerateArg(Args, OPT_fcf_protection_EQ, "full", SA);
1477  else if (Opts.CFProtectionReturn)
1478  GenerateArg(Args, OPT_fcf_protection_EQ, "return", SA);
1479  else if (Opts.CFProtectionBranch)
1480  GenerateArg(Args, OPT_fcf_protection_EQ, "branch", SA);
1481 
1482  if (Opts.IBTSeal)
1483  GenerateArg(Args, OPT_mibt_seal, SA);
1484 
1485  for (const auto &F : Opts.LinkBitcodeFiles) {
1486  bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
1487  F.PropagateAttrs && F.Internalize;
1488  GenerateArg(Args,
1489  Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
1490  F.Filename, SA);
1491  }
1492 
1493  // TODO: Consider removing marshalling annotations from f[no_]emulated_tls.
1494  // That would make it easy to generate the option only **once** if it was
1495  // explicitly set to non-default value.
1496  if (Opts.ExplicitEmulatedTLS) {
1497  GenerateArg(
1498  Args, Opts.EmulatedTLS ? OPT_femulated_tls : OPT_fno_emulated_tls, SA);
1499  }
1500 
1501  if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1502  GenerateArg(Args, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str(), SA);
1503 
1504  if ((Opts.FPDenormalMode != Opts.FP32DenormalMode) ||
1505  (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE()))
1506  GenerateArg(Args, OPT_fdenormal_fp_math_f32_EQ, Opts.FP32DenormalMode.str(),
1507  SA);
1508 
1509  if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
1510  OptSpecifier Opt =
1511  T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
1512  GenerateArg(Args, Opt, SA);
1513  } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
1514  OptSpecifier Opt =
1515  T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
1516  GenerateArg(Args, Opt, SA);
1517  }
1518 
1519  if (Opts.EnableAIXExtendedAltivecABI)
1520  GenerateArg(Args, OPT_mabi_EQ_vec_extabi, SA);
1521 
1522  if (!Opts.OptRecordPasses.empty())
1523  GenerateArg(Args, OPT_opt_record_passes, Opts.OptRecordPasses, SA);
1524 
1525  if (!Opts.OptRecordFormat.empty())
1526  GenerateArg(Args, OPT_opt_record_format, Opts.OptRecordFormat, SA);
1527 
1528  GenerateOptimizationRemark(Args, SA, OPT_Rpass_EQ, "pass",
1529  Opts.OptimizationRemark);
1530 
1531  GenerateOptimizationRemark(Args, SA, OPT_Rpass_missed_EQ, "pass-missed",
1533 
1534  GenerateOptimizationRemark(Args, SA, OPT_Rpass_analysis_EQ, "pass-analysis",
1536 
1537  GenerateArg(Args, OPT_fdiagnostics_hotness_threshold_EQ,
1539  ? Twine(*Opts.DiagnosticsHotnessThreshold)
1540  : "auto",
1541  SA);
1542 
1543  GenerateArg(Args, OPT_fdiagnostics_misexpect_tolerance_EQ,
1544  Twine(*Opts.DiagnosticsMisExpectTolerance), SA);
1545 
1546  for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover))
1547  GenerateArg(Args, OPT_fsanitize_recover_EQ, Sanitizer, SA);
1548 
1549  for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap))
1550  GenerateArg(Args, OPT_fsanitize_trap_EQ, Sanitizer, SA);
1551 
1552  if (!Opts.EmitVersionIdentMetadata)
1553  GenerateArg(Args, OPT_Qn, SA);
1554 
1555  switch (Opts.FiniteLoops) {
1557  break;
1558  case CodeGenOptions::FiniteLoopsKind::Always:
1559  GenerateArg(Args, OPT_ffinite_loops, SA);
1560  break;
1561  case CodeGenOptions::FiniteLoopsKind::Never:
1562  GenerateArg(Args, OPT_fno_finite_loops, SA);
1563  break;
1564  }
1565 }
1566 
1567 bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
1568  InputKind IK,
1569  DiagnosticsEngine &Diags,
1570  const llvm::Triple &T,
1571  const std::string &OutputFile,
1572  const LangOptions &LangOptsRef) {
1573  unsigned NumErrorsBefore = Diags.getNumErrors();
1574 
1575  unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
1576  // TODO: This could be done in Driver
1577  unsigned MaxOptLevel = 3;
1578  if (OptimizationLevel > MaxOptLevel) {
1579  // If the optimization level is not supported, fall back on the default
1580  // optimization
1581  Diags.Report(diag::warn_drv_optimization_value)
1582  << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
1583  OptimizationLevel = MaxOptLevel;
1584  }
1585  Opts.OptimizationLevel = OptimizationLevel;
1586 
1587  // The key paths of codegen options defined in Options.td start with
1588  // "CodeGenOpts.". Let's provide the expected variable name and type.
1589  CodeGenOptions &CodeGenOpts = Opts;
1590  // Some codegen options depend on language options. Let's provide the expected
1591  // variable name and type.
1592  const LangOptions *LangOpts = &LangOptsRef;
1593 
1594 #define CODEGEN_OPTION_WITH_MARSHALLING( \
1595  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
1596  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
1597  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
1598  MERGER, EXTRACTOR, TABLE_INDEX) \
1599  PARSE_OPTION_WITH_MARSHALLING( \
1600  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
1601  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
1602 #include "clang/Driver/Options.inc"
1603 #undef CODEGEN_OPTION_WITH_MARSHALLING
1604 
1605  // At O0 we want to fully disable inlining outside of cases marked with
1606  // 'alwaysinline' that are required for correctness.
1607  if (Opts.OptimizationLevel == 0) {
1608  Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1609  } else if (const Arg *A = Args.getLastArg(options::OPT_finline_functions,
1610  options::OPT_finline_hint_functions,
1611  options::OPT_fno_inline_functions,
1612  options::OPT_fno_inline)) {
1613  // Explicit inlining flags can disable some or all inlining even at
1614  // optimization levels above zero.
1615  if (A->getOption().matches(options::OPT_finline_functions))
1616  Opts.setInlining(CodeGenOptions::NormalInlining);
1617  else if (A->getOption().matches(options::OPT_finline_hint_functions))
1618  Opts.setInlining(CodeGenOptions::OnlyHintInlining);
1619  else
1620  Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1621  } else {
1622  Opts.setInlining(CodeGenOptions::NormalInlining);
1623  }
1624 
1625  // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
1626  // -fdirect-access-external-data.
1627  Opts.DirectAccessExternalData =
1628  Args.hasArg(OPT_fdirect_access_external_data) ||
1629  (!Args.hasArg(OPT_fno_direct_access_external_data) &&
1630  LangOpts->PICLevel == 0);
1631 
1632  if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
1633  unsigned Val =
1634  llvm::StringSwitch<unsigned>(A->getValue())
1635  .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
1636  .Case("line-directives-only", codegenoptions::DebugDirectivesOnly)
1637  .Case("limited", codegenoptions::LimitedDebugInfo)
1638  .Case("standalone", codegenoptions::FullDebugInfo)
1639  .Case("unused-types", codegenoptions::UnusedTypeInfo)
1640  .Default(~0U);
1641  if (Val == ~0U)
1642  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1643  << A->getValue();
1644  else
1645  Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
1646  }
1647 
1648  for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
1649  auto Split = StringRef(Arg).split('=');
1650  Opts.DebugPrefixMap.insert(
1651  {std::string(Split.first), std::string(Split.second)});
1652  }
1653 
1654  for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
1655  auto Split = StringRef(Arg).split('=');
1656  Opts.CoveragePrefixMap.insert(
1657  {std::string(Split.first), std::string(Split.second)});
1658  }
1659 
1660  const llvm::Triple::ArchType DebugEntryValueArchs[] = {
1661  llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
1662  llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
1663  llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
1664 
1665  if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
1666  llvm::is_contained(DebugEntryValueArchs, T.getArch()))
1667  Opts.EmitCallSiteInfo = true;
1668 
1669  if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
1670  Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
1671  << Opts.DIBugsReportFilePath;
1672  Opts.DIBugsReportFilePath = "";
1673  }
1674 
1675  Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
1676  Args.hasArg(OPT_new_struct_path_tbaa);
1677  Opts.OptimizeSize = getOptimizationLevelSize(Args);
1678  Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
1679  if (Opts.SimplifyLibCalls)
1680  Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
1681  Opts.UnrollLoops =
1682  Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
1683  (Opts.OptimizationLevel > 1));
1684  Opts.BinutilsVersion =
1685  std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
1686 
1687  Opts.DebugNameTable = static_cast<unsigned>(
1688  Args.hasArg(OPT_ggnu_pubnames)
1689  ? llvm::DICompileUnit::DebugNameTableKind::GNU
1690  : Args.hasArg(OPT_gpubnames)
1691  ? llvm::DICompileUnit::DebugNameTableKind::Default
1693  if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
1694  StringRef Value = A->getValue();
1695  if (Value != "simple" && Value != "mangled")
1696  Diags.Report(diag::err_drv_unsupported_option_argument)
1697  << A->getOption().getName() << A->getValue();
1698  Opts.setDebugSimpleTemplateNames(
1699  StringRef(A->getValue()) == "simple"
1702  }
1703 
1704  if (!Opts.ProfileInstrumentUsePath.empty())
1706 
1707  if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
1708  Opts.TimePasses = true;
1709 
1710  // -ftime-report= is only for new pass manager.
1711  if (A->getOption().getID() == OPT_ftime_report_EQ) {
1712  StringRef Val = A->getValue();
1713  if (Val == "per-pass")
1714  Opts.TimePassesPerRun = false;
1715  else if (Val == "per-pass-run")
1716  Opts.TimePassesPerRun = true;
1717  else
1718  Diags.Report(diag::err_drv_invalid_value)
1719  << A->getAsString(Args) << A->getValue();
1720  }
1721  }
1722 
1723  Opts.PrepareForLTO = false;
1724  Opts.PrepareForThinLTO = false;
1725  if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
1726  Opts.PrepareForLTO = true;
1727  StringRef S = A->getValue();
1728  if (S == "thin")
1729  Opts.PrepareForThinLTO = true;
1730  else if (S != "full")
1731  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
1732  }
1733  if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
1734  if (IK.getLanguage() != Language::LLVM_IR)
1735  Diags.Report(diag::err_drv_argument_only_allowed_with)
1736  << A->getAsString(Args) << "-x ir";
1737  Opts.ThinLTOIndexFile =
1738  std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
1739  }
1740  if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
1741  Opts.SaveTempsFilePrefix =
1742  llvm::StringSwitch<std::string>(A->getValue())
1743  .Case("obj", OutputFile)
1744  .Default(llvm::sys::path::filename(OutputFile).str());
1745 
1746  // The memory profile runtime appends the pid to make this name more unique.
1747  const char *MemProfileBasename = "memprof.profraw";
1748  if (Args.hasArg(OPT_fmemory_profile_EQ)) {
1749  SmallString<128> Path(
1750  std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
1751  llvm::sys::path::append(Path, MemProfileBasename);
1752  Opts.MemoryProfileOutput = std::string(Path);
1753  } else if (Args.hasArg(OPT_fmemory_profile))
1754  Opts.MemoryProfileOutput = MemProfileBasename;
1755 
1756  memcpy(Opts.CoverageVersion, "408*", 4);
1757  if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
1758  if (Args.hasArg(OPT_coverage_version_EQ)) {
1759  StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
1760  if (CoverageVersion.size() != 4) {
1761  Diags.Report(diag::err_drv_invalid_value)
1762  << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
1763  << CoverageVersion;
1764  } else {
1765  memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
1766  }
1767  }
1768  }
1769  // FIXME: For backend options that are not yet recorded as function
1770  // attributes in the IR, keep track of them so we can embed them in a
1771  // separate data section and use them when building the bitcode.
1772  for (const auto &A : Args) {
1773  // Do not encode output and input.
1774  if (A->getOption().getID() == options::OPT_o ||
1775  A->getOption().getID() == options::OPT_INPUT ||
1776  A->getOption().getID() == options::OPT_x ||
1777  A->getOption().getID() == options::OPT_fembed_bitcode ||
1778  A->getOption().matches(options::OPT_W_Group))
1779  continue;
1780  ArgStringList ASL;
1781  A->render(Args, ASL);
1782  for (const auto &arg : ASL) {
1783  StringRef ArgStr(arg);
1784  Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1785  // using \00 to separate each commandline options.
1786  Opts.CmdArgs.push_back('\0');
1787  }
1788  }
1789 
1790  auto XRayInstrBundles =
1791  Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1792  if (XRayInstrBundles.empty())
1794  else
1795  for (const auto &A : XRayInstrBundles)
1796  parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1797  Diags, Opts.XRayInstrumentationBundle);
1798 
1799  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1800  StringRef Name = A->getValue();
1801  if (Name == "full") {
1802  Opts.CFProtectionReturn = 1;
1803  Opts.CFProtectionBranch = 1;
1804  } else if (Name == "return")
1805  Opts.CFProtectionReturn = 1;
1806  else if (Name == "branch")
1807  Opts.CFProtectionBranch = 1;
1808  else if (Name != "none")
1809  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1810  }
1811 
1812  if (Opts.PrepareForLTO && Args.hasArg(OPT_mibt_seal))
1813  Opts.IBTSeal = 1;
1814 
1815  for (auto *A :
1816  Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1818  F.Filename = A->getValue();
1819  if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1820  F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
1821  // When linking CUDA bitcode, propagate function attributes so that
1822  // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1823  F.PropagateAttrs = true;
1824  F.Internalize = true;
1825  }
1826  Opts.LinkBitcodeFiles.push_back(F);
1827  }
1828 
1829  if (Args.getLastArg(OPT_femulated_tls) ||
1830  Args.getLastArg(OPT_fno_emulated_tls)) {
1831  Opts.ExplicitEmulatedTLS = true;
1832  }
1833 
1834  if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
1835  if (T.isOSAIX()) {
1836  StringRef Name = A->getValue();
1837  if (Name != "global-dynamic")
1838  Diags.Report(diag::err_aix_unsupported_tls_model) << Name;
1839  }
1840  }
1841 
1842  if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1843  StringRef Val = A->getValue();
1844  Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
1845  Opts.FP32DenormalMode = Opts.FPDenormalMode;
1846  if (!Opts.FPDenormalMode.isValid())
1847  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1848  }
1849 
1850  if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
1851  StringRef Val = A->getValue();
1852  Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
1853  if (!Opts.FP32DenormalMode.isValid())
1854  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1855  }
1856 
1857  // X86_32 has -fppc-struct-return and -freg-struct-return.
1858  // PPC32 has -maix-struct-return and -msvr4-struct-return.
1859  if (Arg *A =
1860  Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
1861  OPT_maix_struct_return, OPT_msvr4_struct_return)) {
1862  // TODO: We might want to consider enabling these options on AIX in the
1863  // future.
1864  if (T.isOSAIX())
1865  Diags.Report(diag::err_drv_unsupported_opt_for_target)
1866  << A->getSpelling() << T.str();
1867 
1868  const Option &O = A->getOption();
1869  if (O.matches(OPT_fpcc_struct_return) ||
1870  O.matches(OPT_maix_struct_return)) {
1871  Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1872  } else {
1873  assert(O.matches(OPT_freg_struct_return) ||
1874  O.matches(OPT_msvr4_struct_return));
1875  Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1876  }
1877  }
1878 
1879  if (Arg *A =
1880  Args.getLastArg(OPT_mabi_EQ_vec_default, OPT_mabi_EQ_vec_extabi)) {
1881  if (!T.isOSAIX())
1882  Diags.Report(diag::err_drv_unsupported_opt_for_target)
1883  << A->getSpelling() << T.str();
1884 
1885  const Option &O = A->getOption();
1886  Opts.EnableAIXExtendedAltivecABI = O.matches(OPT_mabi_EQ_vec_extabi);
1887  }
1888 
1889  bool NeedLocTracking = false;
1890 
1891  if (!Opts.OptRecordFile.empty())
1892  NeedLocTracking = true;
1893 
1894  if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
1895  Opts.OptRecordPasses = A->getValue();
1896  NeedLocTracking = true;
1897  }
1898 
1899  if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
1900  Opts.OptRecordFormat = A->getValue();
1901  NeedLocTracking = true;
1902  }
1903 
1904  Opts.OptimizationRemark =
1905  ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
1906 
1908  ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed");
1909 
1911  Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
1912 
1913  NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
1916 
1917  bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
1918  bool UsingProfile = UsingSampleProfile ||
1919  (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
1920 
1921  if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1922  // An IR file will contain PGO as metadata
1924  Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1925  << "-fdiagnostics-show-hotness";
1926 
1927  // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1928  if (auto *arg =
1929  Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
1930  auto ResultOrErr =
1931  llvm::remarks::parseHotnessThresholdOption(arg->getValue());
1932 
1933  if (!ResultOrErr) {
1934  Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
1935  << "-fdiagnostics-hotness-threshold=";
1936  } else {
1937  Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
1938  if ((!Opts.DiagnosticsHotnessThreshold.hasValue() ||
1939  Opts.DiagnosticsHotnessThreshold.getValue() > 0) &&
1940  !UsingProfile)
1941  Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1942  << "-fdiagnostics-hotness-threshold=";
1943  }
1944  }
1945 
1946  if (auto *arg =
1947  Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
1948  auto ResultOrErr = parseToleranceOption(arg->getValue());
1949 
1950  if (!ResultOrErr) {
1951  Diags.Report(diag::err_drv_invalid_diagnotics_misexpect_tolerance)
1952  << "-fdiagnostics-misexpect-tolerance=";
1953  } else {
1954  Opts.DiagnosticsMisExpectTolerance = *ResultOrErr;
1955  if ((!Opts.DiagnosticsMisExpectTolerance.hasValue() ||
1956  Opts.DiagnosticsMisExpectTolerance.getValue() > 0) &&
1957  !UsingProfile)
1958  Diags.Report(diag::warn_drv_diagnostics_misexpect_requires_pgo)
1959  << "-fdiagnostics-misexpect-tolerance=";
1960  }
1961  }
1962 
1963  // If the user requested to use a sample profile for PGO, then the
1964  // backend will need to track source location information so the profile
1965  // can be incorporated into the IR.
1966  if (UsingSampleProfile)
1967  NeedLocTracking = true;
1968 
1969  if (!Opts.StackUsageOutput.empty())
1970  NeedLocTracking = true;
1971 
1972  // If the user requested a flag that requires source locations available in
1973  // the backend, make sure that the backend tracks source location information.
1974  if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
1975  Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
1976 
1977  // Parse -fsanitize-recover= arguments.
1978  // FIXME: Report unrecoverable sanitizers incorrectly specified here.
1979  parseSanitizerKinds("-fsanitize-recover=",
1980  Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
1981  Opts.SanitizeRecover);
1982  parseSanitizerKinds("-fsanitize-trap=",
1983  Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
1984  Opts.SanitizeTrap);
1985 
1986  Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
1987 
1988  if (Args.hasArg(options::OPT_ffinite_loops))
1989  Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
1990  else if (Args.hasArg(options::OPT_fno_finite_loops))
1991  Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
1992 
1993  Opts.EmitIEEENaNCompliantInsts = Args.hasFlag(
1994  options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee, true);
1995  if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
1996  Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
1997 
1998  return Diags.getNumErrors() == NumErrorsBefore;
1999 }
2000 
2001 static void
2005  const DependencyOutputOptions &DependencyOutputOpts = Opts;
2006 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
2007  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2008  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2009  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2010  MERGER, EXTRACTOR, TABLE_INDEX) \
2011  GENERATE_OPTION_WITH_MARSHALLING( \
2012  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2013  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2014 #include "clang/Driver/Options.inc"
2015 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2016 
2018  GenerateArg(Args, OPT_show_includes, SA);
2019 
2020  for (const auto &Dep : Opts.ExtraDeps) {
2021  switch (Dep.second) {
2023  // Sanitizer ignorelist arguments are generated from LanguageOptions.
2024  continue;
2025  case EDK_ModuleFile:
2026  // Module file arguments are generated from FrontendOptions and
2027  // HeaderSearchOptions.
2028  continue;
2029  case EDK_ProfileList:
2030  // Profile list arguments are generated from LanguageOptions via the
2031  // marshalling infrastructure.
2032  continue;
2033  case EDK_DepFileEntry:
2034  GenerateArg(Args, OPT_fdepfile_entry, Dep.first, SA);
2035  break;
2036  }
2037  }
2038 }
2039 
2041  ArgList &Args, DiagnosticsEngine &Diags,
2043  bool ShowLineMarkers) {
2044  unsigned NumErrorsBefore = Diags.getNumErrors();
2045 
2046  DependencyOutputOptions &DependencyOutputOpts = Opts;
2047 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
2048  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2049  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2050  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2051  MERGER, EXTRACTOR, TABLE_INDEX) \
2052  PARSE_OPTION_WITH_MARSHALLING( \
2053  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2054  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2055 #include "clang/Driver/Options.inc"
2056 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2057 
2058  if (Args.hasArg(OPT_show_includes)) {
2059  // Writing both /showIncludes and preprocessor output to stdout
2060  // would produce interleaved output, so use stderr for /showIncludes.
2061  // This behaves the same as cl.exe, when /E, /EP or /P are passed.
2062  if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
2064  else
2066  } else {
2068  }
2069 
2070  // Add sanitizer ignorelists as extra dependencies.
2071  // They won't be discovered by the regular preprocessor, so
2072  // we let make / ninja to know about this implicit dependency.
2073  if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) {
2074  for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) {
2075  StringRef Val = A->getValue();
2076  if (!Val.contains('='))
2077  Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2078  }
2079  if (Opts.IncludeSystemHeaders) {
2080  for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) {
2081  StringRef Val = A->getValue();
2082  if (!Val.contains('='))
2083  Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2084  }
2085  }
2086  }
2087 
2088  // -fprofile-list= dependencies.
2089  for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
2090  Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList);
2091 
2092  // Propagate the extra dependencies.
2093  for (const auto *A : Args.filtered(OPT_fdepfile_entry))
2094  Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry);
2095 
2096  // Only the -fmodule-file=<file> form.
2097  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2098  StringRef Val = A->getValue();
2099  if (!Val.contains('='))
2100  Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile);
2101  }
2102 
2103  return Diags.getNumErrors() == NumErrorsBefore;
2104 }
2105 
2106 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
2107  // Color diagnostics default to auto ("on" if terminal supports) in the driver
2108  // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
2109  // Support both clang's -f[no-]color-diagnostics and gcc's
2110  // -f[no-]diagnostics-colors[=never|always|auto].
2111  enum {
2112  Colors_On,
2113  Colors_Off,
2114  Colors_Auto
2115  } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
2116  for (auto *A : Args) {
2117  const Option &O = A->getOption();
2118  if (O.matches(options::OPT_fcolor_diagnostics)) {
2119  ShowColors = Colors_On;
2120  } else if (O.matches(options::OPT_fno_color_diagnostics)) {
2121  ShowColors = Colors_Off;
2122  } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2123  StringRef Value(A->getValue());
2124  if (Value == "always")
2125  ShowColors = Colors_On;
2126  else if (Value == "never")
2127  ShowColors = Colors_Off;
2128  else if (Value == "auto")
2129  ShowColors = Colors_Auto;
2130  }
2131  }
2132  return ShowColors == Colors_On ||
2133  (ShowColors == Colors_Auto &&
2134  llvm::sys::Process::StandardErrHasColors());
2135 }
2136 
2137 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
2138  DiagnosticsEngine &Diags) {
2139  bool Success = true;
2140  for (const auto &Prefix : VerifyPrefixes) {
2141  // Every prefix must start with a letter and contain only alphanumeric
2142  // characters, hyphens, and underscores.
2143  auto BadChar = llvm::find_if(Prefix, [](char C) {
2144  return !isAlphanumeric(C) && C != '-' && C != '_';
2145  });
2146  if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
2147  Success = false;
2148  Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
2149  Diags.Report(diag::note_drv_verify_prefix_spelling);
2150  }
2151  }
2152  return Success;
2153 }
2154 
2158  const FileSystemOptions &FileSystemOpts = Opts;
2159 
2160 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING( \
2161  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2162  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2163  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2164  MERGER, EXTRACTOR, TABLE_INDEX) \
2165  GENERATE_OPTION_WITH_MARSHALLING( \
2166  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2167  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2168 #include "clang/Driver/Options.inc"
2169 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2170 }
2171 
2172 static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
2173  DiagnosticsEngine &Diags) {
2174  unsigned NumErrorsBefore = Diags.getNumErrors();
2175 
2176  FileSystemOptions &FileSystemOpts = Opts;
2177 
2178 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING( \
2179  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2180  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2181  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2182  MERGER, EXTRACTOR, TABLE_INDEX) \
2183  PARSE_OPTION_WITH_MARSHALLING( \
2184  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2185  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2186 #include "clang/Driver/Options.inc"
2187 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2188 
2189  return Diags.getNumErrors() == NumErrorsBefore;
2190 }
2191 
2192 static void GenerateMigratorArgs(const MigratorOptions &Opts,
2195  const MigratorOptions &MigratorOpts = Opts;
2196 #define MIGRATOR_OPTION_WITH_MARSHALLING( \
2197  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2198  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2199  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2200  MERGER, EXTRACTOR, TABLE_INDEX) \
2201  GENERATE_OPTION_WITH_MARSHALLING( \
2202  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2203  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2204 #include "clang/Driver/Options.inc"
2205 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2206 }
2207 
2208 static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
2209  DiagnosticsEngine &Diags) {
2210  unsigned NumErrorsBefore = Diags.getNumErrors();
2211 
2212  MigratorOptions &MigratorOpts = Opts;
2213 
2214 #define MIGRATOR_OPTION_WITH_MARSHALLING( \
2215  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2216  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2217  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2218  MERGER, EXTRACTOR, TABLE_INDEX) \
2219  PARSE_OPTION_WITH_MARSHALLING( \
2220  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2221  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2222 #include "clang/Driver/Options.inc"
2223 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2224 
2225  return Diags.getNumErrors() == NumErrorsBefore;
2226 }
2227 
2228 void CompilerInvocation::GenerateDiagnosticArgs(
2230  StringAllocator SA, bool DefaultDiagColor) {
2231  const DiagnosticOptions *DiagnosticOpts = &Opts;
2232 #define DIAG_OPTION_WITH_MARSHALLING( \
2233  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2234  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2235  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2236  MERGER, EXTRACTOR, TABLE_INDEX) \
2237  GENERATE_OPTION_WITH_MARSHALLING( \
2238  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2239  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2240 #include "clang/Driver/Options.inc"
2241 #undef DIAG_OPTION_WITH_MARSHALLING
2242 
2243  if (!Opts.DiagnosticSerializationFile.empty())
2244  GenerateArg(Args, OPT_diagnostic_serialized_file,
2245  Opts.DiagnosticSerializationFile, SA);
2246 
2247  if (Opts.ShowColors)
2248  GenerateArg(Args, OPT_fcolor_diagnostics, SA);
2249 
2250  if (Opts.VerifyDiagnostics &&
2251  llvm::is_contained(Opts.VerifyPrefixes, "expected"))
2252  GenerateArg(Args, OPT_verify, SA);
2253 
2254  for (const auto &Prefix : Opts.VerifyPrefixes)
2255  if (Prefix != "expected")
2256  GenerateArg(Args, OPT_verify_EQ, Prefix, SA);
2257 
2258  DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
2259  if (VIU == DiagnosticLevelMask::None) {
2260  // This is the default, don't generate anything.
2261  } else if (VIU == DiagnosticLevelMask::All) {
2262  GenerateArg(Args, OPT_verify_ignore_unexpected, SA);
2263  } else {
2264  if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
2265  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "note", SA);
2266  if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
2267  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "remark", SA);
2268  if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
2269  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "warning", SA);
2270  if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
2271  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "error", SA);
2272  }
2273 
2274  for (const auto &Warning : Opts.Warnings) {
2275  // This option is automatically generated from UndefPrefixes.
2276  if (Warning == "undef-prefix")
2277  continue;
2278  Args.push_back(SA(StringRef("-W") + Warning));
2279  }
2280 
2281  for (const auto &Remark : Opts.Remarks) {
2282  // These arguments are generated from OptimizationRemark fields of
2283  // CodeGenOptions.
2284  StringRef IgnoredRemarks[] = {"pass", "no-pass",
2285  "pass-analysis", "no-pass-analysis",
2286  "pass-missed", "no-pass-missed"};
2287  if (llvm::is_contained(IgnoredRemarks, Remark))
2288  continue;
2289 
2290  Args.push_back(SA(StringRef("-R") + Remark));
2291  }
2292 }
2293 
2294 std::unique_ptr<DiagnosticOptions>
2296  auto DiagOpts = std::make_unique<DiagnosticOptions>();
2297  unsigned MissingArgIndex, MissingArgCount;
2298  InputArgList Args = getDriverOptTable().ParseArgs(
2299  Argv.slice(1), MissingArgIndex, MissingArgCount);
2300  // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
2301  // Any errors that would be diagnosed here will also be diagnosed later,
2302  // when the DiagnosticsEngine actually exists.
2303  (void)ParseDiagnosticArgs(*DiagOpts, Args);
2304  return DiagOpts;
2305 }
2306 
2307 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
2308  DiagnosticsEngine *Diags,
2309  bool DefaultDiagColor) {
2310  Optional<DiagnosticsEngine> IgnoringDiags;
2311  if (!Diags) {
2312  IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(),
2313  new IgnoringDiagConsumer());
2314  Diags = &*IgnoringDiags;
2315  }
2316 
2317  unsigned NumErrorsBefore = Diags->getNumErrors();
2318 
2319  // The key paths of diagnostic options defined in Options.td start with
2320  // "DiagnosticOpts->". Let's provide the expected variable name and type.
2321  DiagnosticOptions *DiagnosticOpts = &Opts;
2322 
2323 #define DIAG_OPTION_WITH_MARSHALLING( \
2324  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2325  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2326  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2327  MERGER, EXTRACTOR, TABLE_INDEX) \
2328  PARSE_OPTION_WITH_MARSHALLING( \
2329  Args, *Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2330  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2331 #include "clang/Driver/Options.inc"
2332 #undef DIAG_OPTION_WITH_MARSHALLING
2333 
2334  llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
2335 
2336  if (Arg *A =
2337  Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
2338  Opts.DiagnosticSerializationFile = A->getValue();
2339  Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
2340 
2341  Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
2342  Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
2343  if (Args.hasArg(OPT_verify))
2344  Opts.VerifyPrefixes.push_back("expected");
2345  // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
2346  // then sort it to prepare for fast lookup using std::binary_search.
2347  if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags))
2348  Opts.VerifyDiagnostics = false;
2349  else
2350  llvm::sort(Opts.VerifyPrefixes);
2353  "-verify-ignore-unexpected=",
2354  Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask);
2355  if (Args.hasArg(OPT_verify_ignore_unexpected))
2356  DiagMask = DiagnosticLevelMask::All;
2357  Opts.setVerifyIgnoreUnexpected(DiagMask);
2358  if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
2359  Opts.TabStop = DiagnosticOptions::DefaultTabStop;
2360  Diags->Report(diag::warn_ignoring_ftabstop_value)
2361  << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
2362  }
2363 
2364  addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
2365  addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
2366 
2367  return Diags->getNumErrors() == NumErrorsBefore;
2368 }
2369 
2370 /// Parse the argument to the -ftest-module-file-extension
2371 /// command-line argument.
2372 ///
2373 /// \returns true on error, false on success.
2374 static bool parseTestModuleFileExtensionArg(StringRef Arg,
2375  std::string &BlockName,
2376  unsigned &MajorVersion,
2377  unsigned &MinorVersion,
2378  bool &Hashed,
2379  std::string &UserInfo) {
2380  SmallVector<StringRef, 5> Args;
2381  Arg.split(Args, ':', 5);
2382  if (Args.size() < 5)
2383  return true;
2384 
2385  BlockName = std::string(Args[0]);
2386  if (Args[1].getAsInteger(10, MajorVersion)) return true;
2387  if (Args[2].getAsInteger(10, MinorVersion)) return true;
2388  if (Args[3].getAsInteger(2, Hashed)) return true;
2389  if (Args.size() > 4)
2390  UserInfo = std::string(Args[4]);
2391  return false;
2392 }
2393 
2394 /// Return a table that associates command line option specifiers with the
2395 /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
2396 /// intentionally missing, as this case is handled separately from other
2397 /// frontend options.
2398 static const auto &getFrontendActionTable() {
2399  static const std::pair<frontend::ActionKind, unsigned> Table[] = {
2400  {frontend::ASTDeclList, OPT_ast_list},
2401 
2402  {frontend::ASTDump, OPT_ast_dump_all_EQ},
2403  {frontend::ASTDump, OPT_ast_dump_all},
2404  {frontend::ASTDump, OPT_ast_dump_EQ},
2405  {frontend::ASTDump, OPT_ast_dump},
2406  {frontend::ASTDump, OPT_ast_dump_lookups},
2407  {frontend::ASTDump, OPT_ast_dump_decl_types},
2408 
2409  {frontend::ASTPrint, OPT_ast_print},
2410  {frontend::ASTView, OPT_ast_view},
2411  {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
2412  {frontend::DumpRawTokens, OPT_dump_raw_tokens},
2413  {frontend::DumpTokens, OPT_dump_tokens},
2414  {frontend::EmitAssembly, OPT_S},
2415  {frontend::EmitBC, OPT_emit_llvm_bc},
2416  {frontend::EmitHTML, OPT_emit_html},
2417  {frontend::EmitLLVM, OPT_emit_llvm},
2418  {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
2419  {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
2420  {frontend::EmitObj, OPT_emit_obj},
2421  {frontend::ExtractAPI, OPT_extract_api},
2422 
2423  {frontend::FixIt, OPT_fixit_EQ},
2424  {frontend::FixIt, OPT_fixit},
2425 
2426  {frontend::GenerateModule, OPT_emit_module},
2427  {frontend::GenerateModuleInterface, OPT_emit_module_interface},
2428  {frontend::GenerateHeaderModule, OPT_emit_header_module},
2429  {frontend::GenerateHeaderUnit, OPT_emit_header_unit},
2430  {frontend::GeneratePCH, OPT_emit_pch},
2431  {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
2432  {frontend::InitOnly, OPT_init_only},
2433  {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
2434  {frontend::ModuleFileInfo, OPT_module_file_info},
2435  {frontend::VerifyPCH, OPT_verify_pch},
2436  {frontend::PrintPreamble, OPT_print_preamble},
2438  {frontend::TemplightDump, OPT_templight_dump},
2439  {frontend::RewriteMacros, OPT_rewrite_macros},
2440  {frontend::RewriteObjC, OPT_rewrite_objc},
2441  {frontend::RewriteTest, OPT_rewrite_test},
2442  {frontend::RunAnalysis, OPT_analyze},
2443  {frontend::MigrateSource, OPT_migrate},
2444  {frontend::RunPreprocessorOnly, OPT_Eonly},
2446  OPT_print_dependency_directives_minimized_source},
2447  };
2448 
2449  return Table;
2450 }
2451 
2452 /// Maps command line option to frontend action.
2454  for (const auto &ActionOpt : getFrontendActionTable())
2455  if (ActionOpt.second == Opt.getID())
2456  return ActionOpt.first;
2457 
2458  return None;
2459 }
2460 
2461 /// Maps frontend action to command line option.
2464  for (const auto &ActionOpt : getFrontendActionTable())
2465  if (ActionOpt.first == ProgramAction)
2466  return OptSpecifier(ActionOpt.second);
2467 
2468  return None;
2469 }
2470 
2471 static void GenerateFrontendArgs(const FrontendOptions &Opts,
2474  bool IsHeader) {
2475  const FrontendOptions &FrontendOpts = Opts;
2476 #define FRONTEND_OPTION_WITH_MARSHALLING( \
2477  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2478  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2479  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2480  MERGER, EXTRACTOR, TABLE_INDEX) \
2481  GENERATE_OPTION_WITH_MARSHALLING( \
2482  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2483  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2484 #include "clang/Driver/Options.inc"
2485 #undef FRONTEND_OPTION_WITH_MARSHALLING
2486 
2487  Optional<OptSpecifier> ProgramActionOpt =
2489 
2490  // Generating a simple flag covers most frontend actions.
2491  std::function<void()> GenerateProgramAction = [&]() {
2492  GenerateArg(Args, *ProgramActionOpt, SA);
2493  };
2494 
2495  if (!ProgramActionOpt) {
2496  // PluginAction is the only program action handled separately.
2497  assert(Opts.ProgramAction == frontend::PluginAction &&
2498  "Frontend action without option.");
2499  GenerateProgramAction = [&]() {
2500  GenerateArg(Args, OPT_plugin, Opts.ActionName, SA);
2501  };
2502  }
2503 
2504  // FIXME: Simplify the complex 'AST dump' command line.
2505  if (Opts.ProgramAction == frontend::ASTDump) {
2506  GenerateProgramAction = [&]() {
2507  // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
2508  // marshalling infrastructure.
2509 
2510  if (Opts.ASTDumpFormat != ADOF_Default) {
2511  StringRef Format;
2512  switch (Opts.ASTDumpFormat) {
2513  case ADOF_Default:
2514  llvm_unreachable("Default AST dump format.");
2515  case ADOF_JSON:
2516  Format = "json";
2517  break;
2518  }
2519 
2520  if (Opts.ASTDumpAll)
2521  GenerateArg(Args, OPT_ast_dump_all_EQ, Format, SA);
2522  if (Opts.ASTDumpDecls)
2523  GenerateArg(Args, OPT_ast_dump_EQ, Format, SA);
2524  } else {
2525  if (Opts.ASTDumpAll)
2526  GenerateArg(Args, OPT_ast_dump_all, SA);
2527  if (Opts.ASTDumpDecls)
2528  GenerateArg(Args, OPT_ast_dump, SA);
2529  }
2530  };
2531  }
2532 
2533  if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
2534  GenerateProgramAction = [&]() {
2535  GenerateArg(Args, OPT_fixit_EQ, Opts.FixItSuffix, SA);
2536  };
2537  }
2538 
2539  GenerateProgramAction();
2540 
2541  for (const auto &PluginArgs : Opts.PluginArgs) {
2542  Option Opt = getDriverOptTable().getOption(OPT_plugin_arg);
2543  const char *Spelling =
2544  SA(Opt.getPrefix() + Opt.getName() + PluginArgs.first);
2545  for (const auto &PluginArg : PluginArgs.second)
2546  denormalizeString(Args, Spelling, SA, Opt.getKind(), 0, PluginArg);
2547  }
2548 
2549  for (const auto &Ext : Opts.ModuleFileExtensions)
2550  if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get()))
2551  GenerateArg(Args, OPT_ftest_module_file_extension_EQ, TestExt->str(), SA);
2552 
2553  if (!Opts.CodeCompletionAt.FileName.empty())
2554  GenerateArg(Args, OPT_code_completion_at, Opts.CodeCompletionAt.ToString(),
2555  SA);
2556 
2557  for (const auto &Plugin : Opts.Plugins)
2558  GenerateArg(Args, OPT_load, Plugin, SA);
2559 
2560  // ASTDumpDecls and ASTDumpAll already handled with ProgramAction.
2561 
2562  for (const auto &ModuleFile : Opts.ModuleFiles)
2563  GenerateArg(Args, OPT_fmodule_file, ModuleFile, SA);
2564 
2565  if (Opts.AuxTargetCPU.hasValue())
2566  GenerateArg(Args, OPT_aux_target_cpu, *Opts.AuxTargetCPU, SA);
2567 
2568  if (Opts.AuxTargetFeatures.hasValue())
2569  for (const auto &Feature : *Opts.AuxTargetFeatures)
2570  GenerateArg(Args, OPT_aux_target_feature, Feature, SA);
2571 
2572  {
2573  StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : "";
2574  StringRef ModuleMap =
2575  Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : "";
2576  StringRef HeaderUnit = "";
2577  switch (Opts.DashX.getHeaderUnitKind()) {
2579  break;
2581  HeaderUnit = "-user";
2582  break;
2584  HeaderUnit = "-system";
2585  break;
2587  HeaderUnit = "-header-unit";
2588  break;
2589  }
2590  StringRef Header = IsHeader ? "-header" : "";
2591 
2592  StringRef Lang;
2593  switch (Opts.DashX.getLanguage()) {
2594  case Language::C:
2595  Lang = "c";
2596  break;
2597  case Language::OpenCL:
2598  Lang = "cl";
2599  break;
2600  case Language::OpenCLCXX:
2601  Lang = "clcpp";
2602  break;
2603  case Language::CUDA:
2604  Lang = "cuda";
2605  break;
2606  case Language::HIP:
2607  Lang = "hip";
2608  break;
2609  case Language::CXX:
2610  Lang = "c++";
2611  break;
2612  case Language::ObjC:
2613  Lang = "objective-c";
2614  break;
2615  case Language::ObjCXX:
2616  Lang = "objective-c++";
2617  break;
2619  Lang = "renderscript";
2620  break;
2621  case Language::Asm:
2622  Lang = "assembler-with-cpp";
2623  break;
2624  case Language::Unknown:
2625  assert(Opts.DashX.getFormat() == InputKind::Precompiled &&
2626  "Generating -x argument for unknown language (not precompiled).");
2627  Lang = "ast";
2628  break;
2629  case Language::LLVM_IR:
2630  Lang = "ir";
2631  break;
2632  case Language::HLSL:
2633  Lang = "hlsl";
2634  break;
2635  }
2636 
2637  GenerateArg(Args, OPT_x,
2638  Lang + HeaderUnit + Header + ModuleMap + Preprocessed, SA);
2639  }
2640 
2641  // OPT_INPUT has a unique class, generate it directly.
2642  for (const auto &Input : Opts.Inputs)
2643  Args.push_back(SA(Input.getFile()));
2644 }
2645 
2646 static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
2647  DiagnosticsEngine &Diags, bool &IsHeaderFile) {
2648  unsigned NumErrorsBefore = Diags.getNumErrors();
2649 
2650  FrontendOptions &FrontendOpts = Opts;
2651 
2652 #define FRONTEND_OPTION_WITH_MARSHALLING( \
2653  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2654  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2655  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2656  MERGER, EXTRACTOR, TABLE_INDEX) \
2657  PARSE_OPTION_WITH_MARSHALLING( \
2658  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
2659  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
2660 #include "clang/Driver/Options.inc"
2661 #undef FRONTEND_OPTION_WITH_MARSHALLING
2662 
2664  if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
2665  OptSpecifier Opt = OptSpecifier(A->getOption().getID());
2667  assert(ProgramAction && "Option specifier not in Action_Group.");
2668 
2669  if (ProgramAction == frontend::ASTDump &&
2670  (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
2671  unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
2672  .CaseLower("default", ADOF_Default)
2673  .CaseLower("json", ADOF_JSON)
2675 
2677  Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
2678  else {
2679  Diags.Report(diag::err_drv_invalid_value)
2680  << A->getAsString(Args) << A->getValue();
2681  Opts.ASTDumpFormat = ADOF_Default;
2682  }
2683  }
2684 
2685  if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ)
2686  Opts.FixItSuffix = A->getValue();
2687 
2688  if (ProgramAction == frontend::GenerateInterfaceStubs) {
2689  StringRef ArgStr =
2690  Args.hasArg(OPT_interface_stub_version_EQ)
2691  ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
2692  : "ifs-v1";
2693  if (ArgStr == "experimental-yaml-elf-v1" ||
2694  ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-ifs-v2" ||
2695  ArgStr == "experimental-tapi-elf-v1") {
2696  std::string ErrorMessage =
2697  "Invalid interface stub format: " + ArgStr.str() +
2698  " is deprecated.";
2699  Diags.Report(diag::err_drv_invalid_value)
2700  << "Must specify a valid interface stub format type, ie: "
2701  "-interface-stub-version=ifs-v1"
2702  << ErrorMessage;
2703  ProgramAction = frontend::ParseSyntaxOnly;
2704  } else if (!ArgStr.startswith("ifs-")) {
2705  std::string ErrorMessage =
2706  "Invalid interface stub format: " + ArgStr.str() + ".";
2707  Diags.Report(diag::err_drv_invalid_value)
2708  << "Must specify a valid interface stub format type, ie: "
2709  "-interface-stub-version=ifs-v1"
2710  << ErrorMessage;
2711  ProgramAction = frontend::ParseSyntaxOnly;
2712  }
2713  }
2714 
2715  Opts.ProgramAction = *ProgramAction;
2716  }
2717 
2718  if (const Arg* A = Args.getLastArg(OPT_plugin)) {
2719  Opts.Plugins.emplace_back(A->getValue(0));
2721  Opts.ActionName = A->getValue();
2722  }
2723  for (const auto *AA : Args.filtered(OPT_plugin_arg))
2724  Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
2725 
2726  for (const std::string &Arg :
2727  Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
2728  std::string BlockName;
2729  unsigned MajorVersion;
2730  unsigned MinorVersion;
2731  bool Hashed;
2732  std::string UserInfo;
2733  if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
2734  MinorVersion, Hashed, UserInfo)) {
2735  Diags.Report(diag::err_test_module_file_extension_format) << Arg;
2736 
2737  continue;
2738  }
2739 
2740  // Add the testing module file extension.
2741  Opts.ModuleFileExtensions.push_back(
2742  std::make_shared<TestModuleFileExtension>(
2743  BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
2744  }
2745 
2746  if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
2747  Opts.CodeCompletionAt =
2748  ParsedSourceLocation::FromString(A->getValue());
2749  if (Opts.CodeCompletionAt.FileName.empty())
2750  Diags.Report(diag::err_drv_invalid_value)
2751  << A->getAsString(Args) << A->getValue();
2752  }
2753 
2754  Opts.Plugins = Args.getAllArgValues(OPT_load);
2755  Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
2756  Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
2757  // Only the -fmodule-file=<file> form.
2758  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2759  StringRef Val = A->getValue();
2760  if (!Val.contains('='))
2761  Opts.ModuleFiles.push_back(std::string(Val));
2762  }
2763 
2765  Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
2766  << "-emit-module";
2767 
2768  if (Args.hasArg(OPT_aux_target_cpu))
2769  Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
2770  if (Args.hasArg(OPT_aux_target_feature))
2771  Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
2772 
2775  Diags.Report(diag::err_drv_argument_not_allowed_with)
2776  << "ARC migration" << "ObjC migration";
2777  }
2778 
2780  if (const Arg *A = Args.getLastArg(OPT_x)) {
2781  StringRef XValue = A->getValue();
2782 
2783  // Parse suffixes:
2784  // '<lang>(-[{header-unit,user,system}-]header|[-module-map][-cpp-output])'.
2785  // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
2786  bool Preprocessed = XValue.consume_back("-cpp-output");
2787  bool ModuleMap = XValue.consume_back("-module-map");
2788  // Detect and consume the header indicator.
2789  bool IsHeader =
2790  XValue != "precompiled-header" && XValue.consume_back("-header");
2791 
2792  // If we have c++-{user,system}-header, that indicates a header unit input
2793  // likewise, if the user put -fmodule-header together with a header with an
2794  // absolute path (header-unit-header).
2796  if (IsHeader || Preprocessed) {
2797  if (XValue.consume_back("-header-unit"))
2799  else if (XValue.consume_back("-system"))
2801  else if (XValue.consume_back("-user"))
2803  }
2804 
2805  // The value set by this processing is an un-preprocessed source which is
2806  // not intended to be a module map or header unit.
2807  IsHeaderFile = IsHeader && !Preprocessed && !ModuleMap &&
2809 
2810  // Principal languages.
2811  DashX = llvm::StringSwitch<InputKind>(XValue)
2812  .Case("c", Language::C)
2813  .Case("cl", Language::OpenCL)
2814  .Case("clcpp", Language::OpenCLCXX)
2815  .Case("cuda", Language::CUDA)
2816  .Case("hip", Language::HIP)
2817  .Case("c++", Language::CXX)
2818  .Case("objective-c", Language::ObjC)
2819  .Case("objective-c++", Language::ObjCXX)
2820  .Case("renderscript", Language::RenderScript)
2821  .Case("hlsl", Language::HLSL)
2822  .Default(Language::Unknown);
2823 
2824  // "objc[++]-cpp-output" is an acceptable synonym for
2825  // "objective-c[++]-cpp-output".
2826  if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap &&
2828  DashX = llvm::StringSwitch<InputKind>(XValue)
2829  .Case("objc", Language::ObjC)
2830  .Case("objc++", Language::ObjCXX)
2831  .Default(Language::Unknown);
2832 
2833  // Some special cases cannot be combined with suffixes.
2834  if (DashX.isUnknown() && !Preprocessed && !IsHeaderFile && !ModuleMap &&
2836  DashX = llvm::StringSwitch<InputKind>(XValue)
2837  .Case("cpp-output", InputKind(Language::C).getPreprocessed())
2838  .Case("assembler-with-cpp", Language::Asm)
2839  .Cases("ast", "pcm", "precompiled-header",
2841  .Case("ir", Language::LLVM_IR)
2842  .Default(Language::Unknown);
2843 
2844  if (DashX.isUnknown())
2845  Diags.Report(diag::err_drv_invalid_value)
2846  << A->getAsString(Args) << A->getValue();
2847 
2848  if (Preprocessed)
2849  DashX = DashX.getPreprocessed();
2850  // A regular header is considered mutually exclusive with a header unit.
2851  if (HUK != InputKind::HeaderUnit_None) {
2852  DashX = DashX.withHeaderUnit(HUK);
2853  IsHeaderFile = true;
2854  } else if (IsHeaderFile)
2855  DashX = DashX.getHeader();
2856  if (ModuleMap)
2857  DashX = DashX.withFormat(InputKind::ModuleMap);
2858  }
2859 
2860  // '-' is the default input if none is given.
2861  std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
2862  Opts.Inputs.clear();
2863  if (Inputs.empty())
2864  Inputs.push_back("-");
2865 
2867  Inputs.size() > 1)
2868  Diags.Report(diag::err_drv_header_unit_extra_inputs) << Inputs[1];
2869 
2870  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
2871  InputKind IK = DashX;
2872  if (IK.isUnknown()) {
2874  StringRef(Inputs[i]).rsplit('.').second);
2875  // FIXME: Warn on this?
2876  if (IK.isUnknown())
2877  IK = Language::C;
2878  // FIXME: Remove this hack.
2879  if (i == 0)
2880  DashX = IK;
2881  }
2882 
2883  bool IsSystem = false;
2884 
2885  // The -emit-module action implicitly takes a module map.
2887  IK.getFormat() == InputKind::Source) {
2889  IsSystem = Opts.IsSystemModule;
2890  }
2891 
2892  Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
2893  }
2894 
2895  Opts.DashX = DashX;
2896 
2897  return Diags.getNumErrors() == NumErrorsBefore;
2898 }
2899 
2901  void *MainAddr) {
2902  std::string ClangExecutable =
2903  llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
2904  return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
2905 }
2906 
2910  const HeaderSearchOptions *HeaderSearchOpts = &Opts;
2911 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING( \
2912  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
2913  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
2914  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
2915  MERGER, EXTRACTOR, TABLE_INDEX) \
2916  GENERATE_OPTION_WITH_MARSHALLING( \
2917  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
2918  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
2919 #include "clang/Driver/Options.inc"
2920 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
2921 
2922  if (Opts.UseLibcxx)
2923  GenerateArg(Args, OPT_stdlib_EQ, "libc++", SA);
2924 
2925  if (!Opts.ModuleCachePath.empty())
2926  GenerateArg(Args, OPT_fmodules_cache_path, Opts.ModuleCachePath, SA);
2927 
2928  for (const auto &File : Opts.PrebuiltModuleFiles)
2929  GenerateArg(Args, OPT_fmodule_file, File.first + "=" + File.second, SA);
2930 
2931  for (const auto &Path : Opts.PrebuiltModulePaths)
2932  GenerateArg(Args, OPT_fprebuilt_module_path, Path, SA);
2933 
2934  for (const auto &Macro : Opts.ModulesIgnoreMacros)
2935  GenerateArg(Args, OPT_fmodules_ignore_macro, Macro.val(), SA);
2936 
2937  auto Matches = [](const HeaderSearchOptions::Entry &Entry,
2939  llvm::Optional<bool> IsFramework,
2940  llvm::Optional<bool> IgnoreSysRoot) {
2941  return llvm::is_contained(Groups, Entry.Group) &&
2942  (!IsFramework || (Entry.IsFramework == *IsFramework)) &&
2943  (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot));
2944  };
2945 
2946  auto It = Opts.UserEntries.begin();
2947  auto End = Opts.UserEntries.end();
2948 
2949  // Add -I..., -F..., and -index-header-map options in order.
2950  for (; It < End &&
2951  Matches(*It, {frontend::IndexHeaderMap, frontend::Angled}, None, true);
2952  ++It) {
2953  OptSpecifier Opt = [It, Matches]() {
2954  if (Matches(*It, frontend::IndexHeaderMap, true, true))
2955  return OPT_F;
2956  if (Matches(*It, frontend::IndexHeaderMap, false, true))
2957  return OPT_I;
2958  if (Matches(*It, frontend::Angled, true, true))
2959  return OPT_F;
2960  if (Matches(*It, frontend::Angled, false, true))
2961  return OPT_I;
2962  llvm_unreachable("Unexpected HeaderSearchOptions::Entry.");
2963  }();
2964 
2965  if (It->Group == frontend::IndexHeaderMap)
2966  GenerateArg(Args, OPT_index_header_map, SA);
2967  GenerateArg(Args, Opt, It->Path, SA);
2968  };
2969 
2970  // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may
2971  // have already been generated as "-I[xx]yy". If that's the case, their
2972  // position on command line was such that this has no semantic impact on
2973  // include paths.
2974  for (; It < End &&
2975  Matches(*It, {frontend::After, frontend::Angled}, false, true);
2976  ++It) {
2977  OptSpecifier Opt =
2978  It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
2979  GenerateArg(Args, Opt, It->Path, SA);
2980  }
2981 
2982  // Note: Some paths that came from "-idirafter=xxyy" may have already been
2983  // generated as "-iwithprefix=xxyy". If that's the case, their position on
2984  // command line was such that this has no semantic impact on include paths.
2985  for (; It < End && Matches(*It, {frontend::After}, false, true); ++It)
2986  GenerateArg(Args, OPT_idirafter, It->Path, SA);
2987  for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It)
2988  GenerateArg(Args, OPT_iquote, It->Path, SA);
2989  for (; It < End && Matches(*It, {frontend::System}, false, None); ++It)
2990  GenerateArg(Args, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
2991  It->Path, SA);
2992  for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
2993  GenerateArg(Args, OPT_iframework, It->Path, SA);
2994  for (; It < End && Matches(*It, {frontend::System}, true, false); ++It)
2995  GenerateArg(Args, OPT_iframeworkwithsysroot, It->Path, SA);
2996 
2997  // Add the paths for the various language specific isystem flags.
2998  for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It)
2999  GenerateArg(Args, OPT_c_isystem, It->Path, SA);
3000  for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It)
3001  GenerateArg(Args, OPT_cxx_isystem, It->Path, SA);
3002  for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It)
3003  GenerateArg(Args, OPT_objc_isystem, It->Path, SA);
3004  for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It)
3005  GenerateArg(Args, OPT_objcxx_isystem, It->Path, SA);
3006 
3007  // Add the internal paths from a driver that detects standard include paths.
3008  // Note: Some paths that came from "-internal-isystem" arguments may have
3009  // already been generated as "-isystem". If that's the case, their position on
3010  // command line was such that this has no semantic impact on include paths.
3011  for (; It < End &&
3012  Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true);
3013  ++It) {
3014  OptSpecifier Opt = It->Group == frontend::System
3015  ? OPT_internal_isystem
3016  : OPT_internal_externc_isystem;
3017  GenerateArg(Args, Opt, It->Path, SA);
3018  }
3019 
3020  assert(It == End && "Unhandled HeaderSearchOption::Entry.");
3021 
3022  // Add the path prefixes which are implicitly treated as being system headers.
3023  for (const auto &P : Opts.SystemHeaderPrefixes) {
3024  OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix
3025  : OPT_no_system_header_prefix;
3026  GenerateArg(Args, Opt, P.Prefix, SA);
3027  }
3028 
3029  for (const std::string &F : Opts.VFSOverlayFiles)
3030  GenerateArg(Args, OPT_ivfsoverlay, F, SA);
3031 }
3032 
3033 static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
3034  DiagnosticsEngine &Diags,
3035  const std::string &WorkingDir) {
3036  unsigned NumErrorsBefore = Diags.getNumErrors();
3037 
3038  HeaderSearchOptions *HeaderSearchOpts = &Opts;
3039 
3040 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING( \
3041  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
3042  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
3043  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
3044  MERGER, EXTRACTOR, TABLE_INDEX) \
3045  PARSE_OPTION_WITH_MARSHALLING( \
3046  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
3047  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
3048 #include "clang/Driver/Options.inc"
3049 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3050 
3051  if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
3052  Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
3053 
3054  // Canonicalize -fmodules-cache-path before storing it.
3055  SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
3056  if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
3057  if (WorkingDir.empty())
3058  llvm::sys::fs::make_absolute(P);
3059  else
3060  llvm::sys::fs::make_absolute(WorkingDir, P);
3061  }
3062  llvm::sys::path::remove_dots(P);
3063  Opts.ModuleCachePath = std::string(P.str());
3064 
3065  // Only the -fmodule-file=<name>=<file> form.
3066  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
3067  StringRef Val = A->getValue();
3068  if (Val.contains('=')) {
3069  auto Split = Val.split('=');
3070  Opts.PrebuiltModuleFiles.insert(
3071  {std::string(Split.first), std::string(Split.second)});
3072  }
3073  }
3074  for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
3075  Opts.AddPrebuiltModulePath(A->getValue());
3076 
3077  for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
3078  StringRef MacroDef = A->getValue();
3079  Opts.ModulesIgnoreMacros.insert(
3080  llvm::CachedHashString(MacroDef.split('=').first));
3081  }
3082 
3083  // Add -I..., -F..., and -index-header-map options in order.
3084  bool IsIndexHeaderMap = false;
3085  bool IsSysrootSpecified =
3086  Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
3087  for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
3088  if (A->getOption().matches(OPT_index_header_map)) {
3089  // -index-header-map applies to the next -I or -F.
3090  IsIndexHeaderMap = true;
3091  continue;
3092  }
3093 
3095  IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
3096 
3097  bool IsFramework = A->getOption().matches(OPT_F);
3098  std::string Path = A->getValue();
3099 
3100  if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
3101  SmallString<32> Buffer;
3102  llvm::sys::path::append(Buffer, Opts.Sysroot,
3103  llvm::StringRef(A->getValue()).substr(1));
3104  Path = std::string(Buffer.str());
3105  }
3106 
3107  Opts.AddPath(Path, Group, IsFramework,
3108  /*IgnoreSysroot*/ true);
3109  IsIndexHeaderMap = false;
3110  }
3111 
3112  // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
3113  StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
3114  for (const auto *A :
3115  Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
3116  if (A->getOption().matches(OPT_iprefix))
3117  Prefix = A->getValue();
3118  else if (A->getOption().matches(OPT_iwithprefix))
3119  Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
3120  else
3121  Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
3122  }
3123 
3124  for (const auto *A : Args.filtered(OPT_idirafter))
3125  Opts.AddPath(A->getValue(), frontend::After, false, true);
3126  for (const auto *A : Args.filtered(OPT_iquote))
3127  Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
3128  for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
3129  Opts.AddPath(A->getValue(), frontend::System, false,
3130  !A->getOption().matches(OPT_iwithsysroot));
3131  for (const auto *A : Args.filtered(OPT_iframework))
3132  Opts.AddPath(A->getValue(), frontend::System, true, true);
3133  for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
3134  Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
3135  /*IgnoreSysRoot=*/false);
3136 
3137  // Add the paths for the various language specific isystem flags.
3138  for (const auto *A : Args.filtered(OPT_c_isystem))
3139  Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
3140  for (const auto *A : Args.filtered(OPT_cxx_isystem))
3141  Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
3142  for (const auto *A : Args.filtered(OPT_objc_isystem))
3143  Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
3144  for (const auto *A : Args.filtered(OPT_objcxx_isystem))
3145  Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
3146 
3147  // Add the internal paths from a driver that detects standard include paths.
3148  for (const auto *A :
3149  Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
3151  if (A->getOption().matches(OPT_internal_externc_isystem))
3153  Opts.AddPath(A->getValue(), Group, false, true);
3154  }
3155 
3156  // Add the path prefixes which are implicitly treated as being system headers.
3157  for (const auto *A :
3158  Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
3159  Opts.AddSystemHeaderPrefix(
3160  A->getValue(), A->getOption().matches(OPT_system_header_prefix));
3161 
3162  for (const auto *A : Args.filtered(OPT_ivfsoverlay))
3163  Opts.AddVFSOverlayFile(A->getValue());
3164 
3165  return Diags.getNumErrors() == NumErrorsBefore;
3166 }
3167 
3168 /// Check if input file kind and language standard are compatible.
3170  const LangStandard &S) {
3171  switch (IK.getLanguage()) {
3172  case Language::Unknown:
3173  case Language::LLVM_IR:
3174  llvm_unreachable("should not parse language flags for this input");
3175 
3176  case Language::C:
3177  case Language::ObjC:
3179  return S.getLanguage() == Language::C;
3180 
3181  case Language::OpenCL:
3182  return S.getLanguage() == Language::OpenCL ||
3183  S.getLanguage() == Language::OpenCLCXX;
3184 
3185  case Language::OpenCLCXX:
3186  return S.getLanguage() == Language::OpenCLCXX;
3187 
3188  case Language::CXX:
3189  case Language::ObjCXX:
3190  return S.getLanguage() == Language::CXX;
3191 
3192  case Language::CUDA:
3193  // FIXME: What -std= values should be permitted for CUDA compilations?
3194  return S.getLanguage() == Language::CUDA ||
3195  S.getLanguage() == Language::CXX;
3196 
3197  case Language::HIP:
3198  return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
3199 
3200  case Language::Asm:
3201  // Accept (and ignore) all -std= values.
3202  // FIXME: The -std= value is not ignored; it affects the tokenization
3203  // and preprocessing rules if we're preprocessing this asm input.
3204  return true;
3205 
3206  case Language::HLSL:
3207  return S.getLanguage() == Language::HLSL;
3208  }
3209 
3210  llvm_unreachable("unexpected input language");
3211 }
3212 
3213 /// Get language name for given input kind.
3214 static StringRef GetInputKindName(InputKind IK) {
3215  switch (IK.getLanguage()) {
3216  case Language::C:
3217  return "C";
3218  case Language::ObjC:
3219  return "Objective-C";
3220  case Language::CXX:
3221  return "C++";
3222  case Language::ObjCXX:
3223  return "Objective-C++";
3224  case Language::OpenCL:
3225  return "OpenCL";
3226  case Language::OpenCLCXX:
3227  return "C++ for OpenCL";
3228  case Language::CUDA:
3229  return "CUDA";
3231  return "RenderScript";
3232  case Language::HIP:
3233  return "HIP";
3234 
3235  case Language::Asm:
3236  return "Asm";
3237  case Language::LLVM_IR:
3238  return "LLVM IR";
3239 
3240  case Language::HLSL:
3241  return "HLSL";
3242 
3243  case Language::Unknown:
3244  break;
3245  }
3246  llvm_unreachable("unknown input language");
3247 }
3248 
3249 void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts,
3251  StringAllocator SA,
3252  const llvm::Triple &T, InputKind IK) {
3253  if (IK.getFormat() == InputKind::Precompiled ||
3254  IK.getLanguage() == Language::LLVM_IR) {
3255  if (Opts.ObjCAutoRefCount)
3256  GenerateArg(Args, OPT_fobjc_arc, SA);
3257  if (Opts.PICLevel != 0)
3258  GenerateArg(Args, OPT_pic_level, Twine(Opts.PICLevel), SA);
3259  if (Opts.PIE)
3260  GenerateArg(Args, OPT_pic_is_pie, SA);
3261  for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3262  GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
3263 
3264  return;
3265  }
3266 
3267  OptSpecifier StdOpt;
3268  switch (Opts.LangStd) {
3269  case LangStandard::lang_opencl10:
3270  case LangStandard::lang_opencl11:
3271  case LangStandard::lang_opencl12:
3272  case LangStandard::lang_opencl20:
3273  case LangStandard::lang_opencl30:
3274  case LangStandard::lang_openclcpp10:
3275  case LangStandard::lang_openclcpp2021:
3276  StdOpt = OPT_cl_std_EQ;
3277  break;
3278  default:
3279  StdOpt = OPT_std_EQ;
3280  break;
3281  }
3282 
3284  GenerateArg(Args, StdOpt, LangStandard.getName(), SA);
3285 
3286  if (Opts.IncludeDefaultHeader)
3287  GenerateArg(Args, OPT_finclude_default_header, SA);
3288  if (Opts.DeclareOpenCLBuiltins)
3289  GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
3290 
3291  const LangOptions *LangOpts = &Opts;
3292 
3293 #define LANG_OPTION_WITH_MARSHALLING( \
3294  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
3295  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
3296  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
3297  MERGER, EXTRACTOR, TABLE_INDEX) \
3298  GENERATE_OPTION_WITH_MARSHALLING( \
3299  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
3300  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
3301 #include "clang/Driver/Options.inc"
3302 #undef LANG_OPTION_WITH_MARSHALLING
3303 
3304  // The '-fcf-protection=' option is generated by CodeGenOpts generator.
3305 
3306  if (Opts.ObjC) {
3307  GenerateArg(Args, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString(), SA);
3308 
3309  if (Opts.GC == LangOptions::GCOnly)
3310  GenerateArg(Args, OPT_fobjc_gc_only, SA);
3311  else if (Opts.GC == LangOptions::HybridGC)
3312  GenerateArg(Args, OPT_fobjc_gc, SA);
3313  else if (Opts.ObjCAutoRefCount == 1)
3314  GenerateArg(Args, OPT_fobjc_arc, SA);
3315 
3316  if (Opts.ObjCWeakRuntime)
3317  GenerateArg(Args, OPT_fobjc_runtime_has_weak, SA);
3318 
3319  if (Opts.ObjCWeak)
3320  GenerateArg(Args, OPT_fobjc_weak, SA);
3321 
3322  if (Opts.ObjCSubscriptingLegacyRuntime)
3323  GenerateArg(Args, OPT_fobjc_subscripting_legacy_runtime, SA);
3324  }
3325 
3326  if (Opts.GNUCVersion != 0) {
3327  unsigned Major = Opts.GNUCVersion / 100 / 100;
3328  unsigned Minor = (Opts.GNUCVersion / 100) % 100;
3329  unsigned Patch = Opts.GNUCVersion % 100;
3330  GenerateArg(Args, OPT_fgnuc_version_EQ,
3331  Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch), SA);
3332  }
3333 
3334  if (Opts.IgnoreXCOFFVisibility)
3335  GenerateArg(Args, OPT_mignore_xcoff_visibility, SA);
3336 
3337  if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) {
3338  GenerateArg(Args, OPT_ftrapv, SA);
3339  GenerateArg(Args, OPT_ftrapv_handler, Opts.OverflowHandler, SA);
3340  } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) {
3341  GenerateArg(Args, OPT_fwrapv, SA);
3342  }
3343 
3344  if (Opts.MSCompatibilityVersion != 0) {
3345  unsigned Major = Opts.MSCompatibilityVersion / 10000000;
3346  unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
3347  unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
3348  GenerateArg(Args, OPT_fms_compatibility_version,
3349  Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor), SA);
3350  }
3351 
3352  if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS()) {
3353  if (!Opts.Trigraphs)
3354  GenerateArg(Args, OPT_fno_trigraphs, SA);
3355  } else {
3356  if (Opts.Trigraphs)
3357  GenerateArg(Args, OPT_ftrigraphs, SA);
3358  }
3359 
3360  if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
3361  GenerateArg(Args, OPT_fblocks, SA);
3362 
3363  if (Opts.ConvergentFunctions &&
3364  !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice))
3365  GenerateArg(Args, OPT_fconvergent_functions, SA);
3366 
3367  if (Opts.NoBuiltin && !Opts.Freestanding)
3368  GenerateArg(Args, OPT_fno_builtin, SA);
3369 
3370  if (!Opts.NoBuiltin)
3371  for (const auto &Func : Opts.NoBuiltinFuncs)
3372  GenerateArg(Args, OPT_fno_builtin_, Func, SA);
3373 
3374  if (Opts.LongDoubleSize == 128)
3375  GenerateArg(Args, OPT_mlong_double_128, SA);
3376  else if (Opts.LongDoubleSize == 64)
3377  GenerateArg(Args, OPT_mlong_double_64, SA);
3378  else if (Opts.LongDoubleSize == 80)
3379  GenerateArg(Args, OPT_mlong_double_80, SA);
3380 
3381  // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
3382 
3383  // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or
3384  // '-fopenmp-targets='.
3385  if (Opts.OpenMP && !Opts.OpenMPSimd) {
3386  GenerateArg(Args, OPT_fopenmp, SA);
3387 
3388  if (Opts.OpenMP != 50)
3389  GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
3390 
3391  if (!Opts.OpenMPUseTLS)
3392  GenerateArg(Args, OPT_fnoopenmp_use_tls, SA);
3393 
3394  if (Opts.OpenMPIsDevice)
3395  GenerateArg(Args, OPT_fopenmp_is_device, SA);
3396 
3397  if (Opts.OpenMPIRBuilder)
3398  GenerateArg(Args, OPT_fopenmp_enable_irbuilder, SA);
3399  }
3400 
3401  if (Opts.OpenMPSimd) {
3402  GenerateArg(Args, OPT_fopenmp_simd, SA);
3403 
3404  if (Opts.OpenMP != 50)
3405  GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
3406  }
3407 
3408  if (Opts.OpenMPThreadSubscription)
3409  GenerateArg(Args, OPT_fopenmp_assume_threads_oversubscription, SA);
3410 
3411  if (Opts.OpenMPTeamSubscription)
3412  GenerateArg(Args, OPT_fopenmp_assume_teams_oversubscription, SA);
3413 
3414  if (Opts.OpenMPTargetDebug != 0)
3415  GenerateArg(Args, OPT_fopenmp_target_debug_EQ,
3416  Twine(Opts.OpenMPTargetDebug), SA);
3417 
3418  if (Opts.OpenMPCUDANumSMs != 0)
3419  GenerateArg(Args, OPT_fopenmp_cuda_number_of_sm_EQ,
3420  Twine(Opts.OpenMPCUDANumSMs), SA);
3421 
3422  if (Opts.OpenMPCUDABlocksPerSM != 0)
3423  GenerateArg(Args, OPT_fopenmp_cuda_blocks_per_sm_EQ,
3424  Twine(Opts.OpenMPCUDABlocksPerSM), SA);
3425 
3426  if (Opts.OpenMPCUDAReductionBufNum != 1024)
3427  GenerateArg(Args, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3428  Twine(Opts.OpenMPCUDAReductionBufNum), SA);
3429 
3430  if (!Opts.OMPTargetTriples.empty()) {
3431  std::string Targets;
3432  llvm::raw_string_ostream OS(Targets);
3433  llvm::interleave(
3434  Opts.OMPTargetTriples, OS,
3435  [&OS](const llvm::Triple &T) { OS << T.str(); }, ",");
3436  GenerateArg(Args, OPT_fopenmp_targets_EQ, OS.str(), SA);
3437  }
3438 
3439  if (!Opts.OMPHostIRFile.empty())
3440  GenerateArg(Args, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile, SA);
3441 
3442  if (Opts.OpenMPCUDAMode)
3443  GenerateArg(Args, OPT_fopenmp_cuda_mode, SA);
3444 
3445  if (Opts.OpenMPCUDAForceFullRuntime)
3446  GenerateArg(Args, OPT_fopenmp_cuda_force_full_runtime, SA);
3447 
3448  // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are
3449  // generated from CodeGenOptions.
3450 
3451  if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast)
3452  GenerateArg(Args, OPT_ffp_contract, "fast", SA);
3453  else if (Opts.DefaultFPContractMode == LangOptions::FPM_On)
3454  GenerateArg(Args, OPT_ffp_contract, "on", SA);
3455  else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off)
3456  GenerateArg(Args, OPT_ffp_contract, "off", SA);
3457  else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas)
3458  GenerateArg(Args, OPT_ffp_contract, "fast-honor-pragmas", SA);
3459 
3460  for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3461  GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
3462 
3463  // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'.
3464  for (const std::string &F : Opts.NoSanitizeFiles)
3465  GenerateArg(Args, OPT_fsanitize_ignorelist_EQ, F, SA);
3466 
3467  if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver3_8)
3468  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "3.8", SA);
3469  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver4)
3470  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "4.0", SA);
3471  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver6)
3472  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "6.0", SA);
3473  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver7)
3474  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "7.0", SA);
3475  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver9)
3476  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "9.0", SA);
3477  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver11)
3478  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "11.0", SA);
3479  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver12)
3480  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "12.0", SA);
3481  else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver14)
3482  GenerateArg(Args, OPT_fclang_abi_compat_EQ, "14.0", SA);
3483 
3484  if (Opts.getSignReturnAddressScope() ==
3486  GenerateArg(Args, OPT_msign_return_address_EQ, "all", SA);
3487  else if (Opts.getSignReturnAddressScope() ==
3489  GenerateArg(Args, OPT_msign_return_address_EQ, "non-leaf", SA);
3490 
3491  if (Opts.getSignReturnAddressKey() ==
3493  GenerateArg(Args, OPT_msign_return_address_key_EQ, "b_key", SA);
3494 
3495  if (Opts.CXXABI)
3496  GenerateArg(Args, OPT_fcxx_abi_EQ, TargetCXXABI::getSpelling(*Opts.CXXABI),
3497  SA);
3498 
3499  if (Opts.RelativeCXXABIVTables)
3500  GenerateArg(Args, OPT_fexperimental_relative_cxx_abi_vtables, SA);
3501  else
3502  GenerateArg(Args, OPT_fno_experimental_relative_cxx_abi_vtables, SA);
3503 
3504  if (Opts.UseTargetPathSeparator)
3505  GenerateArg(Args, OPT_ffile_reproducible, SA);
3506  else
3507  GenerateArg(Args, OPT_fno_file_reproducible, SA);
3508 
3509  for (const auto &MP : Opts.MacroPrefixMap)
3510  GenerateArg(Args, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second, SA);
3511 
3512  if (!Opts.RandstructSeed.empty())
3513  GenerateArg(Args, OPT_frandomize_layout_seed_EQ, Opts.RandstructSeed, SA);
3514 }
3515 
3516 bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
3517  InputKind IK, const llvm::Triple &T,
3518  std::vector<std::string> &Includes,
3519  DiagnosticsEngine &Diags) {
3520  unsigned NumErrorsBefore = Diags.getNumErrors();
3521 
3522  if (IK.getFormat() == InputKind::Precompiled ||
3523  IK.getLanguage() == Language::LLVM_IR) {
3524  // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3525  // PassManager in BackendUtil.cpp. They need to be initialized no matter
3526  // what the input type is.
3527  if (Args.hasArg(OPT_fobjc_arc))
3528  Opts.ObjCAutoRefCount = 1;
3529  // PICLevel and PIELevel are needed during code generation and this should
3530  // be set regardless of the input type.
3531  Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3532  Opts.PIE = Args.hasArg(OPT_pic_is_pie);
3533  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3534  Diags, Opts.Sanitize);
3535 
3536  return Diags.getNumErrors() == NumErrorsBefore;
3537  }
3538 
3539  // Other LangOpts are only initialized when the input is not AST or LLVM IR.
3540  // FIXME: Should we really be parsing this for an Language::Asm input?
3541 
3542  // FIXME: Cleanup per-file based stuff.
3544  if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
3545  LangStd = LangStandard::getLangKind(A->getValue());
3546  if (LangStd == LangStandard::lang_unspecified) {
3547  Diags.Report(diag::err_drv_invalid_value)
3548  << A->getAsString(Args) << A->getValue();
3549  // Report supported standards with short description.
3550  for (unsigned KindValue = 0;
3551  KindValue != LangStandard::lang_unspecified;
3552  ++KindValue) {
3554  static_cast<LangStandard::Kind>(KindValue));
3556  auto Diag = Diags.Report(diag::note_drv_use_standard);
3557  Diag << Std.getName() << Std.getDescription();
3558  unsigned NumAliases = 0;
3559 #define LANGSTANDARD(id, name, lang, desc, features)
3560 #define LANGSTANDARD_ALIAS(id, alias) \
3561  if (KindValue == LangStandard::lang_##id) ++NumAliases;
3562 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3563 #include "clang/Basic/LangStandards.def"
3564  Diag << NumAliases;
3565 #define LANGSTANDARD(id, name, lang, desc, features)
3566 #define LANGSTANDARD_ALIAS(id, alias) \
3567  if (KindValue == LangStandard::lang_##id) Diag << alias;
3568 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3569 #include "clang/Basic/LangStandards.def"
3570  }
3571  }
3572  } else {
3573  // Valid standard, check to make sure language and standard are
3574  // compatible.
3576  if (!IsInputCompatibleWithStandard(IK, Std)) {
3577  Diags.Report(diag::err_drv_argument_not_allowed_with)
3578  << A->getAsString(Args) << GetInputKindName(IK);
3579  }
3580  }
3581  }
3582 
3583  // -cl-std only applies for OpenCL language standards.
3584  // Override the -std option in this case.
3585  if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
3586  LangStandard::Kind OpenCLLangStd
3587  = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
3588  .Cases("cl", "CL", LangStandard::lang_opencl10)
3589  .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10)
3590  .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
3591  .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
3592  .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
3593  .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
3594  .Cases("clc++", "CLC++", LangStandard::lang_openclcpp10)
3595  .Cases("clc++1.0", "CLC++1.0", LangStandard::lang_openclcpp10)
3596  .Cases("clc++2021", "CLC++2021", LangStandard::lang_openclcpp2021)
3598 
3599  if (OpenCLLangStd == LangStandard::lang_unspecified) {
3600  Diags.Report(diag::err_drv_invalid_value)
3601  << A->getAsString(Args) << A->getValue();
3602  }
3603  else
3604  LangStd = OpenCLLangStd;
3605  }
3606 
3607  // These need to be parsed now. They are used to set OpenCL defaults.
3608  Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
3609  Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
3610 
3611  LangOptions::setLangDefaults(Opts, IK.getLanguage(), T, Includes, LangStd);
3612 
3613  // The key paths of codegen options defined in Options.td start with
3614  // "LangOpts->". Let's provide the expected variable name and type.
3615  LangOptions *LangOpts = &Opts;
3616 
3617 #define LANG_OPTION_WITH_MARSHALLING( \
3618  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
3619  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
3620  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
3621  MERGER, EXTRACTOR, TABLE_INDEX) \
3622  PARSE_OPTION_WITH_MARSHALLING( \
3623  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
3624  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
3625 #include "clang/Driver/Options.inc"
3626 #undef LANG_OPTION_WITH_MARSHALLING
3627 
3628  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3629  StringRef Name = A->getValue();
3630  if (Name == "full" || Name == "branch") {
3631  Opts.CFProtectionBranch = 1;
3632  }
3633  }
3634 
3635  if ((Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) &&
3636  !Args.hasArg(OPT_sycl_std_EQ)) {
3637  // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to
3638  // provide -sycl-std=, we want to default it to whatever the default SYCL
3639  // version is. I could not find a way to express this with the options
3640  // tablegen because we still want this value to be SYCL_None when the user
3641  // is not in device or host mode.
3642  Opts.setSYCLVersion(LangOptions::SYCL_Default);
3643  }
3644 
3645  if (Opts.ObjC) {
3646  if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
3647  StringRef value = arg->getValue();
3648  if (Opts.ObjCRuntime.tryParse(value))
3649  Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
3650  }
3651 
3652  if (Args.hasArg(OPT_fobjc_gc_only))
3653  Opts.setGC(LangOptions::GCOnly);
3654  else if (Args.hasArg(OPT_fobjc_gc))
3655  Opts.setGC(LangOptions::HybridGC);
3656  else if (Args.hasArg(OPT_fobjc_arc)) {
3657  Opts.ObjCAutoRefCount = 1;
3658  if (!Opts.ObjCRuntime.allowsARC())
3659  Diags.Report(diag::err_arc_unsupported_on_runtime);
3660  }
3661 
3662  // ObjCWeakRuntime tracks whether the runtime supports __weak, not
3663  // whether the feature is actually enabled. This is predominantly
3664  // determined by -fobjc-runtime, but we allow it to be overridden
3665  // from the command line for testing purposes.
3666  if (Args.hasArg(OPT_fobjc_runtime_has_weak))
3667  Opts.ObjCWeakRuntime = 1;
3668  else
3669  Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
3670 
3671  // ObjCWeak determines whether __weak is actually enabled.
3672  // Note that we allow -fno-objc-weak to disable this even in ARC mode.
3673  if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
3674  if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
3675  assert(!Opts.ObjCWeak);
3676  } else if (Opts.getGC() != LangOptions::NonGC) {
3677  Diags.Report(diag::err_objc_weak_with_gc);
3678  } else if (!Opts.ObjCWeakRuntime) {
3679  Diags.Report(diag::err_objc_weak_unsupported);
3680  } else {
3681  Opts.ObjCWeak = 1;
3682  }
3683  } else if (Opts.ObjCAutoRefCount) {
3684  Opts.ObjCWeak = Opts.ObjCWeakRuntime;
3685  }
3686 
3687  if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
3688  Opts.ObjCSubscriptingLegacyRuntime =
3690  }
3691 
3692  if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
3693  // Check that the version has 1 to 3 components and the minor and patch
3694  // versions fit in two decimal digits.
3695  VersionTuple GNUCVer;
3696  bool Invalid = GNUCVer.tryParse(A->getValue());
3697  unsigned Major = GNUCVer.getMajor();
3698  unsigned Minor = GNUCVer.getMinor().value_or(0);
3699  unsigned Patch = GNUCVer.getSubminor().value_or(0);
3700  if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
3701  Diags.Report(diag::err_drv_invalid_value)
3702  << A->getAsString(Args) << A->getValue();
3703  }
3704  Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
3705  }
3706 
3707  if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility)))
3708  Opts.IgnoreXCOFFVisibility = 1;
3709 
3710  if (Args.hasArg(OPT_ftrapv)) {
3711  Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
3712  // Set the handler, if one is specified.
3713  Opts.OverflowHandler =
3714  std::string(Args.getLastArgValue(OPT_ftrapv_handler));
3715  }
3716  else if (Args.hasArg(OPT_fwrapv))
3717  Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
3718 
3719  Opts.MSCompatibilityVersion = 0;
3720  if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
3721  VersionTuple VT;
3722  if (VT.tryParse(A->getValue()))
3723  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
3724  << A->getValue();
3725  Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
3726  VT.getMinor().value_or(0) * 100000 +
3727  VT.getSubminor().value_or(0);
3728  }
3729 
3730  // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
3731  // is specified, or -std is set to a conforming mode.
3732  // Trigraphs are disabled by default in c++1z onwards.
3733  // For z/OS, trigraphs are enabled by default (without regard to the above).
3734  Opts.Trigraphs =
3735  (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS();
3736  Opts.Trigraphs =
3737  Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
3738 
3739  Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
3740  && Opts.OpenCLVersion == 200);
3741 
3742  Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
3743  Opts.SYCLIsDevice ||
3744  Args.hasArg(OPT_fconvergent_functions);
3745 
3746  Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
3747  if (!Opts.NoBuiltin)
3749  if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
3750  if (A->getOption().matches(options::OPT_mlong_double_64))
3751  Opts.LongDoubleSize = 64;
3752  else if (A->getOption().matches(options::OPT_mlong_double_80))
3753  Opts.LongDoubleSize = 80;
3754  else if (A->getOption().matches(options::OPT_mlong_double_128))
3755  Opts.LongDoubleSize = 128;
3756  else
3757  Opts.LongDoubleSize = 0;
3758  }
3759  if (Opts.FastRelaxedMath)
3760  Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3761 
3762  llvm::sort(Opts.ModuleFeatures);
3763 
3764  // -mrtd option
3765  if (Arg *A = Args.getLastArg(OPT_mrtd)) {
3766  if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
3767  Diags.Report(diag::err_drv_argument_not_allowed_with)
3768  << A->getSpelling() << "-fdefault-calling-conv";
3769  else {
3770  if (T.getArch() != llvm::Triple::x86)
3771  Diags.Report(diag::err_drv_argument_not_allowed_with)
3772  << A->getSpelling() << T.getTriple();
3773  else
3774  Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
3775  }
3776  }
3777 
3778  // Check if -fopenmp is specified and set default version to 5.0.
3779  Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 50 : 0;
3780  // Check if -fopenmp-simd is specified.
3781  bool IsSimdSpecified =
3782  Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
3783  /*Default=*/false);
3784  Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
3785  Opts.OpenMPUseTLS =
3786  Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
3787  Opts.OpenMPIsDevice =
3788  Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
3789  Opts.OpenMPIRBuilder =
3790  Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
3791  bool IsTargetSpecified =
3792  Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
3793 
3794  Opts.ConvergentFunctions = Opts.ConvergentFunctions || Opts.OpenMPIsDevice;
3795 
3796  if (Opts.OpenMP || Opts.OpenMPSimd) {
3797  if (int Version = getLastArgIntValue(
3798  Args, OPT_fopenmp_version_EQ,
3799  (IsSimdSpecified || IsTargetSpecified) ? 50 : Opts.OpenMP, Diags))
3800  Opts.OpenMP = Version;
3801  // Provide diagnostic when a given target is not expected to be an OpenMP
3802  // device or host.
3803  if (!Opts.OpenMPIsDevice) {
3804  switch (T.getArch()) {
3805  default:
3806  break;
3807  // Add unsupported host targets here:
3808  case llvm::Triple::nvptx:
3809  case llvm::Triple::nvptx64:
3810  Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
3811  break;
3812  }
3813  }
3814  }
3815 
3816  // Set the flag to prevent the implementation from emitting device exception
3817  // handling code for those requiring so.
3818  if ((Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN())) ||
3819  Opts.OpenCLCPlusPlus) {
3820 
3821  Opts.Exceptions = 0;
3822  Opts.CXXExceptions = 0;
3823  }
3824  if (Opts.OpenMPIsDevice && T.isNVPTX()) {
3825  Opts.OpenMPCUDANumSMs =
3826  getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
3827  Opts.OpenMPCUDANumSMs, Diags);
3828  Opts.OpenMPCUDABlocksPerSM =
3829  getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
3830  Opts.OpenMPCUDABlocksPerSM, Diags);
3831  Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
3832  Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3833  Opts.OpenMPCUDAReductionBufNum, Diags);
3834  }
3835 
3836  // Set the value of the debugging flag used in the new offloading device RTL.
3837  // Set either by a specific value or to a default if not specified.
3838  if (Opts.OpenMPIsDevice && (Args.hasArg(OPT_fopenmp_target_debug) ||
3839  Args.hasArg(OPT_fopenmp_target_debug_EQ))) {
3840  Opts.OpenMPTargetDebug = getLastArgIntValue(
3841  Args, OPT_fopenmp_target_debug_EQ, Opts.OpenMPTargetDebug, Diags);
3842  if (!Opts.OpenMPTargetDebug && Args.hasArg(OPT_fopenmp_target_debug))
3843  Opts.OpenMPTargetDebug = 1;
3844  }
3845 
3846  if (Opts.OpenMPIsDevice) {
3847  if (Args.hasArg(OPT_fopenmp_assume_teams_oversubscription))
3848  Opts.OpenMPTeamSubscription = true;
3849  if (Args.hasArg(OPT_fopenmp_assume_threads_oversubscription))
3850  Opts.OpenMPThreadSubscription = true;
3851  }
3852 
3853  // Get the OpenMP target triples if any.
3854  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
3855  enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
3856  auto getArchPtrSize = [](const llvm::Triple &T) {
3857  if (T.isArch16Bit())
3858  return Arch16Bit;
3859  if (T.isArch32Bit())
3860  return Arch32Bit;
3861  assert(T.isArch64Bit() && "Expected 64-bit architecture");
3862  return Arch64Bit;
3863  };
3864 
3865  for (unsigned i = 0; i < A->getNumValues(); ++i) {
3866  llvm::Triple TT(A->getValue(i));
3867 
3868  if (TT.getArch() == llvm::Triple::UnknownArch ||
3869  !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
3870  TT.getArch() == llvm::Triple::nvptx ||
3871  TT.getArch() == llvm::Triple::nvptx64 ||
3872  TT.getArch() == llvm::Triple::amdgcn ||
3873  TT.getArch() == llvm::Triple::x86 ||
3874  TT.getArch() == llvm::Triple::x86_64))
3875  Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
3876  else if (getArchPtrSize(T) != getArchPtrSize(TT))
3877  Diags.Report(diag::err_drv_incompatible_omp_arch)
3878  << A->getValue(i) << T.str();
3879  else
3880  Opts.OMPTargetTriples.push_back(TT);
3881  }
3882  }
3883 
3884  // Get OpenMP host file path if any and report if a non existent file is
3885  // found
3886  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
3887  Opts.OMPHostIRFile = A->getValue();
3888  if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
3889  Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
3890  << Opts.OMPHostIRFile;
3891  }
3892 
3893  // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
3894  Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
3895  Args.hasArg(options::OPT_fopenmp_cuda_mode);
3896 
3897  // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
3898  Opts.OpenMPCUDAForceFullRuntime =
3899  Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
3900  Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime);
3901 
3902  // FIXME: Eliminate this dependency.
3903  unsigned Opt = getOptimizationLevel(Args, IK, Diags),
3904  OptSize = getOptimizationLevelSize(Args);
3905  Opts.Optimize = Opt != 0;
3906  Opts.OptimizeSize = OptSize != 0;
3907 
3908  // This is the __NO_INLINE__ define, which just depends on things like the
3909  // optimization level and -fno-inline, not actually whether the backend has
3910  // inlining enabled.
3911  Opts.NoInlineDefine = !Opts.Optimize;
3912  if (Arg *InlineArg = Args.getLastArg(
3913  options::OPT_finline_functions, options::OPT_finline_hint_functions,
3914  options::OPT_fno_inline_functions, options::OPT_fno_inline))
3915  if (InlineArg->getOption().matches(options::OPT_fno_inline))
3916  Opts.NoInlineDefine = true;
3917 
3918  if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
3919  StringRef Val = A->getValue();
3920  if (Val == "fast")
3921  Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3922  else if (Val == "on")
3923  Opts.setDefaultFPContractMode(LangOptions::FPM_On);
3924  else if (Val == "off")
3925  Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
3926  else if (Val == "fast-honor-pragmas")
3927  Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
3928  else
3929  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3930  }
3931 
3932  // Parse -fsanitize= arguments.
3933  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3934  Diags, Opts.Sanitize);
3935  Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ);
3936  std::vector<std::string> systemIgnorelists =
3937  Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ);
3938  Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(),
3939  systemIgnorelists.begin(),
3940  systemIgnorelists.end());
3941 
3942  if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
3943  Opts.setClangABICompat(LangOptions::ClangABI::Latest);
3944 
3945  StringRef Ver = A->getValue();
3946  std::pair<StringRef, StringRef> VerParts = Ver.split('.');
3947  unsigned Major, Minor = 0;
3948 
3949  // Check the version number is valid: either 3.x (0 <= x <= 9) or
3950  // y or y.0 (4 <= y <= current version).
3951  if (!VerParts.first.startswith("0") &&
3952  !VerParts.first.getAsInteger(10, Major) &&
3953  3 <= Major && Major <= CLANG_VERSION_MAJOR &&
3954  (Major == 3 ? VerParts.second.size() == 1 &&
3955  !VerParts.second.getAsInteger(10, Minor)
3956  : VerParts.first.size() == Ver.size() ||
3957  VerParts.second == "0")) {
3958  // Got a valid version number.
3959  if (Major == 3 && Minor <= 8)
3960  Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
3961  else if (Major <= 4)
3962  Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
3963  else if (Major <= 6)
3964  Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
3965  else if (Major <= 7)
3966  Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
3967  else if (Major <= 9)
3968  Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
3969  else if (Major <= 11)
3970  Opts.setClangABICompat(LangOptions::ClangABI::Ver11);
3971  else if (Major <= 12)
3972  Opts.setClangABICompat(LangOptions::ClangABI::Ver12);
3973  else if (Major <= 14)
3974  Opts.setClangABICompat(LangOptions::ClangABI::Ver14);
3975  } else if (Ver != "latest") {
3976  Diags.Report(diag::err_drv_invalid_value)
3977  << A->getAsString(Args) << A->getValue();
3978  }
3979  }
3980 
3981  if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
3982  StringRef SignScope = A->getValue();
3983 
3984  if (SignScope.equals_insensitive("none"))
3985  Opts.setSignReturnAddressScope(
3987  else if (SignScope.equals_insensitive("all"))
3988  Opts.setSignReturnAddressScope(
3990  else if (SignScope.equals_insensitive("non-leaf"))
3991  Opts.setSignReturnAddressScope(
3993  else
3994  Diags.Report(diag::err_drv_invalid_value)
3995  << A->getAsString(Args) << SignScope;
3996 
3997  if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
3998  StringRef SignKey = A->getValue();
3999  if (!SignScope.empty() && !SignKey.empty()) {
4000  if (SignKey.equals_insensitive("a_key"))
4001  Opts.setSignReturnAddressKey(
4003  else if (SignKey.equals_insensitive("b_key"))
4004  Opts.setSignReturnAddressKey(
4006  else
4007  Diags.Report(diag::err_drv_invalid_value)
4008  << A->getAsString(Args) << SignKey;
4009  }
4010  }
4011  }
4012 
4013  // The value can be empty, which indicates the system default should be used.
4014  StringRef CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ);
4015  if (!CXXABI.empty()) {
4016  if (!TargetCXXABI::isABI(CXXABI)) {
4017  Diags.Report(diag::err_invalid_cxx_abi) << CXXABI;
4018  } else {
4021  Diags.Report(diag::err_unsupported_cxx_abi) << CXXABI << T.str();
4022  else
4023  Opts.CXXABI = Kind;
4024  }
4025  }
4026 
4027  Opts.RelativeCXXABIVTables =
4028  Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables,
4029  options::OPT_fno_experimental_relative_cxx_abi_vtables,
4031 
4032  for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
4033  auto Split = StringRef(A).split('=');
4034  Opts.MacroPrefixMap.insert(
4035  {std::string(Split.first), std::string(Split.second)});
4036  }
4037 
4038  Opts.UseTargetPathSeparator =
4039  !Args.getLastArg(OPT_fno_file_reproducible) &&
4040  (Args.getLastArg(OPT_ffile_compilation_dir_EQ) ||
4041  Args.getLastArg(OPT_fmacro_prefix_map_EQ) ||
4042  Args.getLastArg(OPT_ffile_reproducible));
4043 
4044  // Error if -mvscale-min is unbounded.
4045  if (Arg *A = Args.getLastArg(options::OPT_mvscale_min_EQ)) {
4046  unsigned VScaleMin;
4047  if (StringRef(A->getValue()).getAsInteger(10, VScaleMin) || VScaleMin == 0)
4048  Diags.Report(diag::err_cc1_unbounded_vscale_min);
4049  }
4050 
4051  if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_file_EQ)) {
4052  std::ifstream SeedFile(A->getValue(0));
4053 
4054  if (!SeedFile.is_open())
4055  Diags.Report(diag::err_drv_cannot_open_randomize_layout_seed_file)
4056  << A->getValue(0);
4057 
4058  std::getline(SeedFile, Opts.RandstructSeed);
4059  }
4060 
4061  if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_EQ))
4062  Opts.RandstructSeed = A->getValue(0);
4063 
4064  return Diags.getNumErrors() == NumErrorsBefore;
4065 }
4066 
4068  switch (Action) {
4069  case frontend::ASTDeclList:
4070  case frontend::ASTDump:
4071  case frontend::ASTPrint:
4072  case frontend::ASTView:
4074  case frontend::EmitBC:
4075  case frontend::EmitHTML:
4076  case frontend::EmitLLVM:
4079  case frontend::EmitObj:
4080  case frontend::ExtractAPI:
4081  case frontend::FixIt:
4086  case frontend::GeneratePCH:
4090  case frontend::VerifyPCH:
4092  case frontend::RewriteObjC:
4093  case frontend::RewriteTest:
4094  case frontend::RunAnalysis:
4097  return false;
4098 
4101  case frontend::DumpTokens:
4102  case frontend::InitOnly:
4108  return true;
4109  }
4110  llvm_unreachable("invalid frontend action");
4111 }
4112 
4116  const LangOptions &LangOpts,
4117  const FrontendOptions &FrontendOpts,
4118  const CodeGenOptions &CodeGenOpts) {
4119  PreprocessorOptions *PreprocessorOpts = &Opts;
4120 
4121 #define PREPROCESSOR_OPTION_WITH_MARSHALLING( \
4122  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4123  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4124  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4125  MERGER, EXTRACTOR, TABLE_INDEX) \
4126  GENERATE_OPTION_WITH_MARSHALLING( \
4127  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
4128  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
4129 #include "clang/Driver/Options.inc"
4130 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4131 
4132  if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
4133  GenerateArg(Args, OPT_pch_through_hdrstop_use, SA);
4134 
4135  for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
4136  GenerateArg(Args, OPT_error_on_deserialized_pch_decl, D, SA);
4137 
4138  if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
4139  GenerateArg(Args, OPT_preamble_bytes_EQ,
4140  Twine(Opts.PrecompiledPreambleBytes.first) + "," +
4141  (Opts.PrecompiledPreambleBytes.second ? "1" : "0"),
4142  SA);
4143 
4144  for (const auto &M : Opts.Macros) {
4145  // Don't generate __CET__ macro definitions. They are implied by the
4146  // -fcf-protection option that is generated elsewhere.
4147  if (M.first == "__CET__=1" && !M.second &&
4148  !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
4149  continue;
4150  if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
4151  !CodeGenOpts.CFProtectionBranch)
4152  continue;
4153  if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
4154  CodeGenOpts.CFProtectionBranch)
4155  continue;
4156 
4157  GenerateArg(Args, M.second ? OPT_U : OPT_D, M.first, SA);
4158  }
4159 
4160  for (const auto &I : Opts.Includes) {
4161  // Don't generate OpenCL includes. They are implied by other flags that are
4162  // generated elsewhere.
4163  if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
4164  ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
4165  I == "opencl-c.h"))
4166  continue;
4167  // Don't generate HLSL includes. They are implied by other flags that are
4168  // generated elsewhere.
4169  if (LangOpts.HLSL && I == "hlsl.h")
4170  continue;
4171 
4172  GenerateArg(Args, OPT_include, I, SA);
4173  }
4174 
4175  for (const auto &CI : Opts.ChainedIncludes)
4176  GenerateArg(Args, OPT_chain_include, CI, SA);
4177 
4178  for (const auto &RF : Opts.RemappedFiles)
4179  GenerateArg(Args, OPT_remap_file, RF.first + ";" + RF.second, SA);
4180 
4181  // Don't handle LexEditorPlaceholders. It is implied by the action that is
4182  // generated elsewhere.
4183 }
4184 
4185 static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
4186  DiagnosticsEngine &Diags,
4188  const FrontendOptions &FrontendOpts) {
4189  unsigned NumErrorsBefore = Diags.getNumErrors();
4190 
4191  PreprocessorOptions *PreprocessorOpts = &Opts;
4192 
4193 #define PREPROCESSOR_OPTION_WITH_MARSHALLING( \
4194  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4195  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4196  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4197  MERGER, EXTRACTOR, TABLE_INDEX) \
4198  PARSE_OPTION_WITH_MARSHALLING( \
4199  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
4200  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
4201 #include "clang/Driver/Options.inc"
4202 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4203 
4204  Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
4205  Args.hasArg(OPT_pch_through_hdrstop_use);
4206 
4207  for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
4208  Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
4209 
4210  if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
4211  StringRef Value(A->getValue());
4212  size_t Comma = Value.find(',');
4213  unsigned Bytes = 0;
4214  unsigned EndOfLine = 0;
4215 
4216  if (Comma == StringRef::npos ||
4217  Value.substr(0, Comma).getAsInteger(10, Bytes) ||
4218  Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
4219  Diags.Report(diag::err_drv_preamble_format);
4220  else {
4221  Opts.PrecompiledPreambleBytes.first = Bytes;
4222  Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
4223  }
4224  }
4225 
4226  // Add the __CET__ macro if a CFProtection option is set.
4227  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
4228  StringRef Name = A->getValue();
4229  if (Name == "branch")
4230  Opts.addMacroDef("__CET__=1");
4231  else if (Name == "return")
4232  Opts.addMacroDef("__CET__=2");
4233  else if (Name == "full")
4234  Opts.addMacroDef("__CET__=3");
4235  }
4236 
4237  // Add macros from the command line.
4238  for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
4239  if (A->getOption().matches(OPT_D))
4240  Opts.addMacroDef(A->getValue());
4241  else
4242  Opts.addMacroUndef(A->getValue());
4243  }
4244 
4245  // Add the ordered list of -includes.
4246  for (const auto *A : Args.filtered(OPT_include))
4247  Opts.Includes.emplace_back(A->getValue());
4248 
4249  for (const auto *A : Args.filtered(OPT_chain_include))
4250  Opts.ChainedIncludes.emplace_back(A->getValue());
4251 
4252  for (const auto *A : Args.filtered(OPT_remap_file)) {
4253  std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
4254 
4255  if (Split.second.empty()) {
4256  Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
4257  continue;
4258  }
4259 
4260  Opts.addRemappedFile(Split.first, Split.second);
4261  }
4262 
4263  // Always avoid lexing editor placeholders when we're just running the
4264  // preprocessor as we never want to emit the
4265  // "editor placeholder in source file" error in PP only mode.
4267  Opts.LexEditorPlaceholders = false;
4268 
4269  return Diags.getNumErrors() == NumErrorsBefore;
4270 }
4271 
4275  const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4276 
4277 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING( \
4278  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4279  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4280  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4281  MERGER, EXTRACTOR, TABLE_INDEX) \
4282  GENERATE_OPTION_WITH_MARSHALLING( \
4283  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
4284  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
4285 #include "clang/Driver/Options.inc"
4286 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4287 
4288  bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
4289  if (Generate_dM)
4290  GenerateArg(Args, OPT_dM, SA);
4291  if (!Generate_dM && Opts.ShowMacros)
4292  GenerateArg(Args, OPT_dD, SA);
4293  if (Opts.DirectivesOnly)
4294  GenerateArg(Args, OPT_fdirectives_only, SA);
4295 }
4296 
4298  ArgList &Args, DiagnosticsEngine &Diags,
4300  unsigned NumErrorsBefore = Diags.getNumErrors();
4301 
4302  PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4303 
4304 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING( \
4305  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4306  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4307  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4308  MERGER, EXTRACTOR, TABLE_INDEX) \
4309  PARSE_OPTION_WITH_MARSHALLING( \
4310  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
4311  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
4312 #include "clang/Driver/Options.inc"
4313 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4314 
4315  Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
4316  Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
4317  Opts.DirectivesOnly = Args.hasArg(OPT_fdirectives_only);
4318 
4319  return Diags.getNumErrors() == NumErrorsBefore;
4320 }
4321 
4322 static void GenerateTargetArgs(const TargetOptions &Opts,
4325  const TargetOptions *TargetOpts = &Opts;
4326 #define TARGET_OPTION_WITH_MARSHALLING( \
4327  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4328  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4329  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4330  MERGER, EXTRACTOR, TABLE_INDEX) \
4331  GENERATE_OPTION_WITH_MARSHALLING( \
4332  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
4333  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
4334 #include "clang/Driver/Options.inc"
4335 #undef TARGET_OPTION_WITH_MARSHALLING
4336 
4337  if (!Opts.SDKVersion.empty())
4338  GenerateArg(Args, OPT_target_sdk_version_EQ, Opts.SDKVersion.getAsString(),
4339  SA);
4340  if (!Opts.DarwinTargetVariantSDKVersion.empty())
4341  GenerateArg(Args, OPT_darwin_target_variant_sdk_version_EQ,
4342  Opts.DarwinTargetVariantSDKVersion.getAsString(), SA);
4343 }
4344 
4345 static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
4346  DiagnosticsEngine &Diags) {
4347  unsigned NumErrorsBefore = Diags.getNumErrors();
4348 
4349  TargetOptions *TargetOpts = &Opts;
4350 
4351 #define TARGET_OPTION_WITH_MARSHALLING( \
4352  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
4353  HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
4354  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
4355  MERGER, EXTRACTOR, TABLE_INDEX) \
4356  PARSE_OPTION_WITH_MARSHALLING( \
4357  Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
4358  IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
4359 #include "clang/Driver/Options.inc"
4360 #undef TARGET_OPTION_WITH_MARSHALLING
4361 
4362  if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
4363  llvm::VersionTuple Version;
4364  if (Version.tryParse(A->getValue()))
4365  Diags.Report(diag::err_drv_invalid_value)
4366  << A->getAsString(Args) << A->getValue();
4367  else
4368  Opts.SDKVersion = Version;
4369  }
4370  if (Arg *A =
4371  Args.getLastArg(options::OPT_darwin_target_variant_sdk_version_EQ)) {
4372  llvm::VersionTuple Version;
4373  if (Version.tryParse(A->getValue()))
4374  Diags.Report(diag::err_drv_invalid_value)
4375  << A->getAsString(Args) << A->getValue();
4376  else
4377  Opts.DarwinTargetVariantSDKVersion = Version;
4378  }
4379 
4380  return Diags.getNumErrors() == NumErrorsBefore;
4381 }
4382 
4383 bool CompilerInvocation::CreateFromArgsImpl(
4384  CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs,
4385  DiagnosticsEngine &Diags, const char *Argv0) {
4386  unsigned NumErrorsBefore = Diags.getNumErrors();
4387 
4388  // Parse the arguments.
4389  const OptTable &Opts = getDriverOptTable();
4390  const unsigned IncludedFlagsBitmask = options::CC1Option;
4391  unsigned MissingArgIndex, MissingArgCount;
4392  InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
4393  MissingArgCount, IncludedFlagsBitmask);
4394  LangOptions &LangOpts = *Res.getLangOpts();
4395 
4396  // Check for missing argument error.
4397  if (MissingArgCount)
4398  Diags.Report(diag::err_drv_missing_argument)
4399  << Args.getArgString(MissingArgIndex) << MissingArgCount;
4400 
4401  // Issue errors on unknown arguments.
4402  for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
4403  auto ArgString = A->getAsString(Args);
4404  std::string Nearest;
4405  if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
4406  Diags.Report(diag::err_drv_unknown_argument) << ArgString;
4407  else
4408  Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
4409  << ArgString << Nearest;
4410  }
4411 
4412  ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags);
4413  ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags);
4414  ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
4415  ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
4416  /*DefaultDiagColor=*/false);
4417  ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile);
4418  // FIXME: We shouldn't have to pass the DashX option around here
4419  InputKind DashX = Res.getFrontendOpts().DashX;
4420  ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
4421  llvm::Triple T(Res.getTargetOpts().Triple);
4422  ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags,
4424 
4425  ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
4426  Diags);
4428  LangOpts.ObjCExceptions = 1;
4429 
4430  for (auto Warning : Res.getDiagnosticOpts().Warnings) {
4431  if (Warning == "misexpect" &&
4432  !Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation())) {
4433  Res.getCodeGenOpts().MisExpect = true;
4434  }
4435  }
4436 
4437  if (LangOpts.CUDA) {
4438  // During CUDA device-side compilation, the aux triple is the
4439  // triple used for host compilation.
4440  if (LangOpts.CUDAIsDevice)
4442  }
4443 
4444  // Set the triple of the host for OpenMP device compile.
4445  if (LangOpts.OpenMPIsDevice)
4447 
4448  ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
4450 
4451  // FIXME: Override value name discarding when asan or msan is used because the
4452  // backend passes depend on the name of the alloca in order to print out
4453  // names.
4454  Res.getCodeGenOpts().DiscardValueNames &=
4455  !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4456  !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
4457  !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
4458  !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
4459 
4460  ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
4462  Res.getFrontendOpts());
4465 
4469  if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
4470  Res.getDependencyOutputOpts().Targets.empty())
4471  Diags.Report(diag::err_fe_dependency_file_requires_MT);
4472 
4473  // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
4474  if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
4475  !Res.getLangOpts()->Sanitize.empty()) {
4476  Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
4477  Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
4478  }
4479 
4480  // Store the command-line for using in the CodeView backend.
4481  Res.getCodeGenOpts().Argv0 = Argv0;
4482  append_range(Res.getCodeGenOpts().CommandLineArgs, CommandLineArgs);
4483 
4484  FixupInvocation(Res, Diags, Args, DashX);
4485 
4486  return Diags.getNumErrors() == NumErrorsBefore;
4487 }
4488 
4490  ArrayRef<const char *> CommandLineArgs,
4491  DiagnosticsEngine &Diags,
4492  const char *Argv0) {
4493  CompilerInvocation DummyInvocation;
4494 
4495  return RoundTrip(
4496  [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
4497  DiagnosticsEngine &Diags, const char *Argv0) {
4498  return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
4499  },
4500  [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
4501  StringAllocator SA) { Invocation.generateCC1CommandLine(Args, SA); },
4502  Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
4503 }
4504 
4506  // FIXME: Consider using SHA1 instead of MD5.
4507  llvm::HashBuilder<llvm::MD5, llvm::support::endianness::native> HBuilder;
4508 
4509  // Note: For QoI reasons, the things we use as a hash here should all be
4510  // dumped via the -module-info flag.
4511 
4512  // Start the signature with the compiler version.
4513  HBuilder.add(getClangFullRepositoryVersion());
4514 
4515  // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
4516  // and getClangFullRepositoryVersion() doesn't include git revision.
4518 
4519  // Extend the signature with the language options
4520 #define LANGOPT(Name, Bits, Default, Description) HBuilder.add(LangOpts->Name);
4521 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4522  HBuilder.add(static_cast<unsigned>(LangOpts->get##Name()));
4523 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
4524 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
4525 #include "clang/Basic/LangOptions.def"
4526 
4527  HBuilder.addRange(LangOpts->ModuleFeatures);
4528 
4529  HBuilder.add(LangOpts->ObjCRuntime);
4530  HBuilder.addRange(LangOpts->CommentOpts.BlockCommandNames);
4531 
4532  // Extend the signature with the target options.
4533  HBuilder.add(TargetOpts->Triple, TargetOpts->CPU, TargetOpts->TuneCPU,
4534  TargetOpts->ABI);
4535  HBuilder.addRange(TargetOpts->FeaturesAsWritten);
4536 
4537  // Extend the signature with preprocessor options.
4538  const PreprocessorOptions &ppOpts = getPreprocessorOpts();
4539  HBuilder.add(ppOpts.UsePredefines, ppOpts.DetailedRecord);
4540 
4541  const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
4542  for (const auto &Macro : getPreprocessorOpts().Macros) {
4543  // If we're supposed to ignore this macro for the purposes of modules,
4544  // don't put it into the hash.
4545  if (!hsOpts.ModulesIgnoreMacros.empty()) {
4546  // Check whether we're ignoring this macro.
4547  StringRef MacroDef = Macro.first;
4548  if (hsOpts.ModulesIgnoreMacros.count(
4549  llvm::CachedHashString(MacroDef.split('=').first)))
4550  continue;
4551  }
4552 
4553  HBuilder.add(Macro);
4554  }
4555 
4556  // Extend the signature with the sysroot and other header search options.
4557  HBuilder.add(hsOpts.Sysroot, hsOpts.ModuleFormat, hsOpts.UseDebugInfo,
4559  hsOpts.UseStandardCXXIncludes, hsOpts.UseLibcxx,
4561  HBuilder.add(hsOpts.ResourceDir);
4562 
4563  if (hsOpts.ModulesStrictContextHash) {
4564  HBuilder.addRange(hsOpts.SystemHeaderPrefixes);
4565  HBuilder.addRange(hsOpts.UserEntries);
4566 
4567  const DiagnosticOptions &diagOpts = getDiagnosticOpts();
4568 #define DIAGOPT(Name, Bits, Default) HBuilder.add(diagOpts.Name);
4569 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4570  HBuilder.add(diagOpts.get##Name());
4571 #include "clang/Basic/DiagnosticOptions.def"
4572 #undef DIAGOPT
4573 #undef ENUM_DIAGOPT
4574  }
4575 
4576  // Extend the signature with the user build path.
4577  HBuilder.add(hsOpts.ModuleUserBuildPath);
4578 
4579  // Extend the signature with the module file extensions.
4580  for (const auto &ext : getFrontendOpts().ModuleFileExtensions)
4581  ext->hashExtension(HBuilder);
4582 
4583  // When compiling with -gmodules, also hash -fdebug-prefix-map as it
4584  // affects the debug info in the PCM.
4585  if (getCodeGenOpts().DebugTypeExtRefs)
4586  HBuilder.addRange(getCodeGenOpts().DebugPrefixMap);
4587 
4588  // Extend the signature with the enabled sanitizers, if at least one is
4589  // enabled. Sanitizers which cannot affect AST generation aren't hashed.
4590  SanitizerSet SanHash = LangOpts->Sanitize;
4591  SanHash.clear(getPPTransparentSanitizers());
4592  if (!SanHash.empty())
4593  HBuilder.add(SanHash.Mask);
4594 
4595  llvm::MD5::MD5Result Result;
4596  HBuilder.getHasher().final(Result);
4597  uint64_t Hash = Result.high() ^ Result.low();
4598  return toString(llvm::APInt(64, Hash), 36, /*Signed=*/false);
4599 }
4600 
4603  llvm::Triple T(TargetOpts->Triple);
4604 
4607  GenerateAnalyzerArgs(*AnalyzerOpts, Args, SA);
4608  GenerateDiagnosticArgs(*DiagnosticOpts, Args, SA, false);
4609  GenerateFrontendArgs(FrontendOpts, Args, SA, LangOpts->IsHeaderFile);
4610  GenerateTargetArgs(*TargetOpts, Args, SA);
4612  GenerateLangArgs(*LangOpts, Args, SA, T, FrontendOpts.DashX);
4613  GenerateCodeGenArgs(CodeGenOpts, Args, SA, T, FrontendOpts.OutputFile,
4614  &*LangOpts);
4616  CodeGenOpts);
4620 }
4621 
4624  DiagnosticsEngine &Diags) {
4625  return createVFSFromCompilerInvocation(CI, Diags,
4626  llvm::vfs::getRealFileSystem());
4627 }
4628 
4631  const CompilerInvocation &CI, DiagnosticsEngine &Diags,
4633  if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
4634  return BaseFS;
4635 
4637  // earlier vfs files are on the bottom
4638  for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
4639  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
4640  Result->getBufferForFile(File);
4641  if (!Buffer) {
4642  Diags.Report(diag::err_missing_vfs_overlay_file) << File;
4643  continue;
4644  }
4645 
4646  IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
4647  std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
4648  /*DiagContext*/ nullptr, Result);
4649  if (!FS) {
4650  Diags.Report(diag::err_invalid_vfs_overlay) << File;
4651  continue;
4652  }
4653 
4654  Result = FS;
4655  }
4656  return Result;
4657 }
clang::CodeGenOptions::BinutilsVersion
std::string BinutilsVersion
Definition: CodeGenOptions.h:125
clang::InputKind::HeaderUnitKind
HeaderUnitKind
Definition: FrontendOptions.h:170
clang::CompilerInvocationValueBase::FileSystemOpts
FileSystemOptions FileSystemOpts
Options controlling file system operations.
Definition: CompilerInvocation.h:147
clang::TargetOptions::HostTriple
std::string HostTriple
When compiling for the device side, contains the triple used to compile for the host.
Definition: TargetOptions.h:33
clang::Language::CUDA
@ CUDA
clang::LangOptions::DCC_FastCall
@ DCC_FastCall
Definition: LangOptions.h:132
clang::DependencyOutputOptions
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
Definition: DependencyOutputOptions.h:33
clang::CodeGenOptions::Argv0
const char * Argv0
Executable and command-line used to create a given CompilerInvocation.
Definition: CodeGenOptions.h:404
normalizeSimpleEnum
static llvm::Optional< unsigned > normalizeSimpleEnum(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args, DiagnosticsEngine &Diags)
Definition: CompilerInvocation.cpp:290
Builtins.h
clang::LangOptions::CurrentModule
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:417
AnalyzerOptions.h
clang::InputKind::HeaderUnit_User
@ HeaderUnit_User
Definition: FrontendOptions.h:172
max
__DEVICE__ int max(int __a, int __b)
Definition: __clang_cuda_math.h:196
clang::CompilerInvocationRefBase::getTargetOpts
TargetOptions & getTargetOpts()
Definition: CompilerInvocation.h:107
clang::CodeGenOptions::CoveragePrefixMap
std::map< std::string, std::string > CoveragePrefixMap
Definition: CodeGenOptions.h:184
ParseOptimizationRemark
static CodeGenOptions::OptRemark ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args, OptSpecifier OptEQ, StringRef Name)
Parse a remark command line argument.
Definition: CompilerInvocation.cpp:1179
FrontendPluginRegistry.h
is_uint64_t_convertible
static constexpr bool is_uint64_t_convertible()
Definition: CompilerInvocation.cpp:199
Visibility.h
clang::LangOptions::ExceptionHandlingKind::None
@ None
clang::AnalyzerOptions::getRegisteredPackages
static std::vector< StringRef > getRegisteredPackages(bool IncludeExperimental=false)
Retrieves the list of packages generated from Checkers.td.
Definition: AnalyzerOptions.h:421
clang::CompilerInvocationValueBase::getCodeGenOpts
CodeGenOptions & getCodeGenOpts()
Definition: CompilerInvocation.h:159
clang::Builtin::Context::isBuiltinFunc
static bool isBuiltinFunc(llvm::StringRef Name)
Returns true if this is a libc/libm function without the '__builtin_' prefix.
Definition: Builtins.cpp:51
clang::interp::APInt
llvm::APInt APInt
Definition: Integral.h:27
clang::ParsedSourceLocation::FromString
static ParsedSourceLocation FromString(StringRef Str)
Construct a parsed source location from a string; the Filename is empty on error.
Definition: CommandLineSourceLoc.h:32
ObjCRuntime.h
clang::frontend::EmitAssembly
@ EmitAssembly
Emit a .s file.
Definition: FrontendOptions.h:58
denormalizeStringVector
static void denormalizeStringVector(SmallVectorImpl< const char * > &Args, const char *Spelling, CompilerInvocation::StringAllocator SA, Option::OptionClass OptClass, unsigned TableIndex, const std::vector< std::string > &Values)
Definition: CompilerInvocation.cpp:367
clang::DiagnosticOptions::DiagnosticSerializationFile
std::string DiagnosticSerializationFile
The file to serialize diagnostics to (non-appending).
Definition: DiagnosticOptions.h:107
TestModuleFileExtension.h
clang::FrontendOptions::ObjCMT_None
@ ObjCMT_None
Definition: FrontendOptions.h:363
clang::LangOptions::getOpenCLCompatibleVersion
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:55
clang::DeclaratorContext::File
@ File
Driver.h
parseToleranceOption
Expected< Optional< uint64_t > > parseToleranceOption(StringRef Arg)
Definition: CompilerInvocation.cpp:116
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::DiagnosticsEngine::setClient
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
Definition: Diagnostic.cpp:111
clang::PreprocessorOptions
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Definition: PreprocessorOptions.h:65
addDiagnosticArgs
static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, OptSpecifier GroupWithValue, std::vector< std::string > &Diagnostics)
Definition: CompilerInvocation.cpp:770
clang::frontend::GenerateHeaderModule
@ GenerateHeaderModule
Generate pre-compiled module from a set of header files.
Definition: FrontendOptions.h:91
clang::getLastArgIntValue
int getLastArgIntValue(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier Id, int Default, DiagnosticsEngine *Diags=nullptr, unsigned Base=0)
Return the value of the last argument as an integer, or a default.
clang::AnalyzerOptions::AnalysisConstraintsOpt
AnalysisConstraints AnalysisConstraintsOpt
Definition: AnalyzerOptions.h:196
clang::frontend::RewriteTest
@ RewriteTest
Rewriter playground.
Definition: FrontendOptions.h:130
clang::CompilerInvocationRefBase::TargetOpts
std::shared_ptr< TargetOptions > TargetOpts
Options controlling the target.
Definition: CompilerInvocation.h:83
clang::DependencyOutputOptions::ExtraDeps
std::vector< std::pair< std::string, ExtraDepKind > > ExtraDeps
A list of extra dependencies (filename and kind) to be used for every target.
Definition: DependencyOutputOptions.h:68
makeFlagToValueNormalizer
static auto makeFlagToValueNormalizer(T Value)
Definition: CompilerInvocation.cpp:206
normalizeSimpleNegativeFlag
static Optional< bool > normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned, const ArgList &Args, DiagnosticsEngine &)
Definition: CompilerInvocation.cpp:180
clang::XRayInstrSet::Mask
XRayInstrMask Mask
Definition: XRayInstr.h:65
clang::CodeGenOptions::SanitizeRecover
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
Definition: CodeGenOptions.h:350
clang::FrontendOptions::ProgramAction
frontend::ActionKind ProgramAction
The frontend action to perform.
Definition: FrontendOptions.h:445
clang::LangOptions::ClangABI::Latest
@ Latest
Conform to the underlying platform's C and C++ ABIs as closely as we can.
getFrontendAction
static Optional< frontend::ActionKind > getFrontendAction(OptSpecifier &Opt)
Maps command line option to frontend action.
Definition: CompilerInvocation.cpp:2453
clang::ParseDiagnosticArgs
bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args, DiagnosticsEngine *Diags=nullptr, bool DefaultDiagColor=true)
Fill out Opts based on the options given in Args.
Diag
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Definition: LiteralSupport.cpp:78
clang::CodeGenOptions::OptimizationRemarkAnalysis
OptRemark OptimizationRemarkAnalysis
Selected optimizations for which we should enable optimization analyses.
Definition: CodeGenOptions.h:343
clang::FrontendOptions::ShowStats
unsigned ShowStats
Show frontend performance metrics and statistics.
Definition: FrontendOptions.h:281
clang::CompilerInvocationRefBase::CompilerInvocationRefBase
CompilerInvocationRefBase()
Definition: CompilerInvocation.cpp:128
clang::HeaderSearchOptions::Entry::IgnoreSysRoot
unsigned IgnoreSysRoot
IgnoreSysRoot - This is false if an absolute path should be treated relative to the sysroot,...
Definition: HeaderSearchOptions.h:78
clang::DiagnosticLevelMask::Error
@ Error
clang::ObjCRuntime::getKind
Kind getKind() const
Definition: ObjCRuntime.h:77
llvm::SmallVector< StringRef, 16 >
mergeMaskValue
static T mergeMaskValue(T KeyPath, U Value)
Definition: CompilerInvocation.cpp:413
GenerateArg
static void GenerateArg(SmallVectorImpl< const char * > &Args, llvm::opt::OptSpecifier OptSpecifier, CompilerInvocation::StringAllocator SA)
Definition: CompilerInvocation.cpp:613
clang::if
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
Definition: RecursiveASTVisitor.h:1098
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::LangOptions::OverflowHandler
std::string OverflowHandler
The name of the handler function to be called when -ftrapv is specified.
Definition: LangOptions.h:407
clang::LangOptions::ClangABI::Ver11
@ Ver11
Attempt to be ABI-compatible with code generated by Clang 11.0.x (git 2e10b7a39b93).
getOptimizationLevelSize
static unsigned getOptimizationLevelSize(ArgList &Args)
Definition: CompilerInvocation.cpp:597
clang::DiagnosticsEngine::isIgnored
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:910
clang::driver::Action
Action - Represent an abstract compilation step to perform.
Definition: Action.h:47
clang::CodeGenOptions::CommandLineArgs
std::vector< std::string > CommandLineArgs
Definition: CodeGenOptions.h:405
clang::FrontendOptions::PluginArgs
std::map< std::string, std::vector< std::string > > PluginArgs
Args to pass to the plugins.
Definition: FrontendOptions.h:455
clang::FrontendOptions::ARCMTAction
enum clang::FrontendOptions::@188 ARCMTAction
GenerateFileSystemArgs
static void GenerateFileSystemArgs(const FileSystemOptions &Opts, SmallVectorImpl< const char * > &Args, CompilerInvocation::StringAllocator SA)
Definition: CompilerInvocation.cpp:2155
parseShowColorsArgs
static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor)
Definition: CompilerInvocation.cpp:2106
clang::frontend::ModuleFileInfo
@ ModuleFileInfo
Dump information about a module file.
Definition: FrontendOptions.h:106
clang::CodeGenOptions::hasSanitizeCoverage
bool hasSanitizeCoverage() const
Definition: CodeGenOptions.h:480
clang::HeaderSearchOptions::UseStandardSystemIncludes
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
Definition: HeaderSearchOptions.h:191
clang::codegenoptions::DebugTemplateNamesKind::Simple
@ Simple
clang::codegenoptions::UnusedTypeInfo
@ UnusedTypeInfo
Generate debug info for types that may be unused in the source (-fno-eliminate-unused-debug-types).
Definition: DebugInfoOptions.h:48
clang::frontend::RunPreprocessorOnly
@ RunPreprocessorOnly
Just lex, no output.
Definition: FrontendOptions.h:142
Filename
StringRef Filename
Definition: Format.cpp:2572
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
clang::Language::OpenCLCXX
@ OpenCLCXX
GetInputKindName
static StringRef GetInputKindName(InputKind IK)
Get language name for given input kind.
Definition: CompilerInvocation.cpp:3214
clang::CodeGenOptions::DIBugsReportFilePath
std::string DIBugsReportFilePath
The file to use for dumping bug report by Debugify for original debug info.
Definition: CodeGenOptions.h:191
clang::CodeGenOptions::SampleProfileFile
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
Definition: CodeGenOptions.h:251
memcpy
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
Definition: __clang_cuda_device_functions.h:1549
clang::CodeGenOptions::SaveTempsFilePrefix
std::string SaveTempsFilePrefix
Prefix to use for -save-temps output.
Definition: CodeGenOptions.h:273
getAllNoBuiltinFuncValues
static void getAllNoBuiltinFuncValues(ArgList &Args, std::vector< std::string > &Funcs)
Definition: CompilerInvocation.cpp:796
clang::LangOptions::CXXABI
llvm::Optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
Definition: LangOptions.h:450
clang::LangOptions::FPM_On
@ FPM_On
Definition: LangOptions.h:253
clang::LangOptions::SignReturnAddressScopeKind::NonLeaf
@ NonLeaf
Sign the return address of functions that spill LR.
clang::PreprocessorOutputOptions::ShowCPP
unsigned ShowCPP
Print normal preprocessed output.
Definition: PreprocessorOutputOptions.h:18
ParseDependencyOutputArgs
static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, frontend::ActionKind Action, bool ShowLineMarkers)
Definition: CompilerInvocation.cpp:2040
checkVerifyPrefixes
static bool checkVerifyPrefixes(const std::vector< std::string > &VerifyPrefixes, DiagnosticsEngine &Diags)
Definition: CompilerInvocation.cpp:2137
clang::LangOptions::SignReturnAddressScopeKind::None
@ None
No signing for any function.
clang::InputKind::withHeaderUnit
InputKind withHeaderUnit(HeaderUnitKind HU) const
Definition: FrontendOptions.h:209
clang::codegenoptions::NoDebugInfo
@ NoDebugInfo
Don't generate debug info.
Definition: DebugInfoOptions.h:22
clang::codegenoptions::DebugTemplateNamesKind::Mangled
@ Mangled
llvm::Optional< bool >
clang::CompilerInvocationRefBase::getHeaderSearchOpts
HeaderSearchOptions & getHeaderSearchOpts()
Definition: CompilerInvocation.h:112
denormalizeSimpleFlag
static void denormalizeSimpleFlag(SmallVectorImpl< const char * > &Args, const char *Spelling, CompilerInvocation::StringAllocator, Option::OptionClass, unsigned,...)
The tblgen-erated code passes in a fifth parameter of an arbitrary type, but denormalizeSimpleFlags n...
Definition: CompilerInvocation.cpp:192
clang::driver::options::CC1Option
@ CC1Option
Definition: Options.h:31
clang::serialization::VERSION_MAJOR
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition: ASTBitCodes.h:44
findValueTableByValue
static Optional< SimpleEnumValue > findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value)
Definition: CompilerInvocation.cpp:282
clang::CodeGenOptions::CodeModel
std::string CodeModel
The code model to use (-mcmodel).
Definition: CodeGenOptions.h:147
clang::frontend::ASTDump
@ ASTDump
Parse ASTs and dump them.
Definition: FrontendOptions.h:40
ParseFrontendArgs
static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, bool &IsHeaderFile)
Definition: CompilerInvocation.cpp:2646
clang::LangOptions::GCOnly
@ GCOnly
Definition: LangOptions.h:83
clang::tooling::X
static ToolExecutorPluginRegistry::Add< AllTUsToolExecutorPlugin > X("all-TUs", "Runs FrontendActions on all TUs in the compilation database. " "Tool results are stored in memory.")
llvm::Expected
Definition: LLVM.h:41
clang::LangOptions::DCC_None
@ DCC_None
Definition: LangOptions.h:130
clang::PreprocessorOptions::DetailedRecord
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
Definition: PreprocessorOptions.h:77
clang::diag::Group
Group
Definition: DiagnosticCategories.h:23
ParseMigratorArgs
static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args, DiagnosticsEngine &Diags)
Definition: CompilerInvocation.cpp:2208
GenerateMigratorArgs
static void GenerateMigratorArgs(const MigratorOptions &Opts, SmallVectorImpl< const char * > &Args, CompilerInvocation::StringAllocator SA)
Definition: CompilerInvocation.cpp:2192
clang::Language::Asm
@ Asm
Assembly: we accept this only so that we can preprocess it.
clang::LangOptions::getOpenCLVersionString
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
Definition: LangOptions.cpp:71
clang::FileSystemOptions::WorkingDir
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
Definition: FileSystemOptions.h:26
clang::LangOptions::MacroPrefixMap
std::map< std::string, std::string, std::greater< std::string > > MacroPrefixMap
A prefix map for FILE, BASE_FILE and __builtin_FILE().
Definition: LangOptions.h:432
clang::InputKind
The kind of a file that we've been handed as an input.
Definition: FrontendOptions.h:151
clang::frontend::CSystem
@ CSystem
Like System, but only used for C.
Definition: HeaderSearchOptions.h:49
clang::PreprocessorOutputOptions::ShowLineMarkers
unsigned ShowLineMarkers
Show #line markers.
Definition: PreprocessorOutputOptions.h:20
clang::frontend::VerifyPCH
@ VerifyPCH
Load and verify that a PCH file is usable.
Definition: FrontendOptions.h:109
clang::AnalyzerOptions::AnalysisPurgeOpt
AnalysisPurgeMode AnalysisPurgeOpt
Definition: AnalyzerOptions.h:198
clang::CompilerInvocationRefBase::LangOpts
std::shared_ptr< LangOptions > LangOpts
Options controlling the language variant.
Definition: CompilerInvocation.h:80
End
SourceLocation End
Definition: USRLocFinder.cpp:167
clang::frontend::PluginAction
@ PluginAction
Run a plugin action,.
Definition: FrontendOptions.h:115
clang::HeaderSearchOptions::ModulesValidateDiagnosticOptions
unsigned ModulesValidateDiagnosticOptions
Definition: HeaderSearchOptions.h:217
clang::frontend::RewriteObjC
@ RewriteObjC
ObjC->C Rewriter.
Definition: FrontendOptions.h:127
clang::InputKind::Source
@ Source
Definition: FrontendOptions.h:162
clang::FrontendOptions::AuxTargetFeatures
Optional< std::vector< std::string > > AuxTargetFeatures
Auxiliary target features for CUDA/HIP compilation.
Definition: FrontendOptions.h:494
GenerateAnalyzerArgs
static void GenerateAnalyzerArgs(AnalyzerOptions &Opts, SmallVectorImpl< const char * > &Args, CompilerInvocation::StringAllocator SA)
Definition: CompilerInvocation.cpp:803
CompilerInvocation.h
clang::XRayInstrSet
Definition: XRayInstr.h:47
clang::PreprocessorOptions::Includes
std::vector< std::string > Includes
Definition: PreprocessorOptions.h:68
clang::ObjCRuntime::allowsWeak
bool allowsWeak() const
Does this runtime allow the use of __weak?
Definition: ObjCRuntime.h:283
PreprocessorOutputOptions.h
extractMaskValue
static T extractMaskValue(T KeyPath)
Definition: CompilerInvocation.cpp:422
clang::frontend::IndexHeaderMap
@ IndexHeaderMap
Like Angled, but marks header maps used when building frameworks.
Definition: HeaderSearchOptions.h:40
clang::codegenoptions::DebugDirectivesOnly
@ DebugDirectivesOnly
Emit only debug directives with the line numbers data.
Definition: DebugInfoOptions.h:31
clang::CompilerInvocationValueBase::CodeGenOpts
CodeGenOptions CodeGenOpts
Options controlling IRgen and the backend.
Definition: CompilerInvocation.h:141
getStringOption
static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config, StringRef OptionName, StringRef DefaultVal)
Definition: CompilerInvocation.cpp:1046
clang::FrontendOptions::Inputs
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
Definition: FrontendOptions.h:426
clang::LangOptions::SignReturnAddressKeyKind::AKey
@ AKey
Return address signing uses APIA key.
clang::ParsedSourceLocation::FileName
std::string FileName
Definition: CommandLineSourceLoc.h:25
clang::HeaderSearchOptions::UseDebugInfo
unsigned UseDebugInfo
Whether the module includes debug information (-gmodules).
Definition: HeaderSearchOptions.h:215
clang::frontend::ObjCSystem
@ ObjCSystem
Like System, but only used for ObjC.
Definition: HeaderSearchOptions.h:55
clang::CodeGenOptions::SRCK_OnStack
@ SRCK_OnStack
Definition: CodeGenOptions.h:81
clang::frontend::GeneratePCH
@ GeneratePCH
Generate pre-compiled header.
Definition: FrontendOptions.h:97
isStrictlyPreprocessorAction
static bool isStrictlyPreprocessorAction(frontend::ActionKind Action)
Definition: CompilerInvocation.cpp:4067
clang::FileSystemOptions
Keeps track of options that affect how file operations are performed.
Definition: FileSystemOptions.h:22
clang::SanitizerSet::Mask
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:176
clang::PreprocessorOptions::PCHWithHdrStopCreate
bool PCHWithHdrStopCreate
When true, we are creating a PCH or creating the PCH object while expecting a #pragma hdrstop to sepa...
Definition: PreprocessorOptions.h:87
uint64_t
unsigned long uint64_t
Definition: hlsl_basic_types.h:24
clang::LangStandard::Kind
Kind
Definition: LangStandard.h:69
clang::getPPTransparentSanitizers
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
Definition: Sanitizers.h:192
CodeGenOptions.h
U
clang::ObjCRuntime::FragileMacOSX
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:40
clang::CodeGenOptions::NoBuiltinFuncs
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
Definition: CodeGenOptions.h:359
clang::frontend::ASTView
@ ASTView
Parse ASTs and view them in Graphviz.
Definition: FrontendOptions.h:46
clang::frontend::ExternCSystem
@ ExternCSystem
Like System, but headers are implicitly wrapped in extern "C".
Definition: HeaderSearchOptions.h:46
clang::LangOptions::SanitizeCoverage
bool SanitizeCoverage
Is at least one coverage instrumentation type enabled.
Definition: LangOptions.h:370
clang::AnalyzerOptions::ConfigTable
llvm::StringMap< std::string > ConfigTable
Definition: AnalyzerOptions.h:153
clang::XRayInstrKind::All
constexpr XRayInstrMask All
Definition: XRayInstr.h:43
normalizeStringIntegral
static Optional< IntTy > normalizeStringIntegral(OptSpecifier Opt, int, const ArgList &Args, DiagnosticsEngine &Diags)
Definition: CompilerInvocation.cpp:346
clang::LangStandard::getLangKind
static Kind getLangKind(StringRef Name)
Definition: LangStandards.cpp:31
getProgramActionOpt
static Optional< OptSpecifier > getProgramActionOpt(frontend::ActionKind ProgramAction)
Maps frontend action to command line option.
Definition: CompilerInvocation.cpp:2463
clang::FrontendOptions::AuxTargetCPU
Optional< std::string > AuxTargetCPU
Auxiliary target CPU for CUDA/HIP compilation.
Definition: FrontendOptions.h:491
clang::LangOptions::SOB_Trapping
@ SOB_Trapping
Definition: LangOptions.h:99
initOption
static void initOption(AnalyzerOptions::ConfigTable &Config, DiagnosticsEngine *Diags, StringRef &OptionField, StringRef Name, StringRef DefaultVal)
Definition: CompilerInvocation.cpp:1051
clang::FrontendOptions::ASTDumpFormat
ASTDumpOutputFormat ASTDumpFormat
Specifies the output format of the AST.
Definition: FrontendOptions.h:353
clang::LangOptions::ClangABI::Ver12
@ Ver12
Attempt to be ABI-compatible with code generated by Clang 12.0.x (git 8e464dd76bef).
clang::frontend::System
@ System
Like Angled, but marks system directories.
Definition: HeaderSearchOptions.h:43
clang::frontend::ASTPrint
@ ASTPrint
Parse ASTs and print them.
Definition: FrontendOptions.h:43
clang::CompilerInvocationRefBase
The base class of CompilerInvocation with reference semantics.
Definition: CompilerInvocation.h:77
clang::Decl::Kind
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:86
clang::Language::RenderScript
@ RenderScript
clang::HeaderSearchOptions::Entry::IsFramework
unsigned IsFramework
Definition: HeaderSearchOptions.h:73
clang::FrontendOptions::ASTDumpDecls
unsigned ASTDumpDecls
Whether we include declaration dumps in AST dumps.
Definition: FrontendOptions.h:318
denormalizeSimpleEnum
static void denormalizeSimpleEnum(SmallVectorImpl< const char * > &Args, const char *Spelling, CompilerInvocation::StringAllocator SA, Option::OptionClass OptClass, unsigned TableIndex, T Value)
Definition: CompilerInvocation.cpp:327
normalizeStringVector
static Optional< std::vector< std::string > > normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args, DiagnosticsEngine &)
Definition: CompilerInvocation.cpp:362
clang::EDK_ModuleFile
@ EDK_ModuleFile
Definition: DependencyOutputOptions.h:27
clang::CodeGenOptions::RK_DisabledEverything
@ RK_DisabledEverything
Definition: CodeGenOptions.h:303
clang::frontend::RunAnalysis
@ RunAnalysis
Run one or more source code analyses.
Definition: FrontendOptions.h:133
clang::HeaderSearchOptions::ModulesStrictContextHash
unsigned ModulesStrictContextHash
Whether we should include all things that could impact the module in the hash.
Definition: HeaderSearchOptions.h:226
DiagnosticDriver.h
clang::CompilerInvocationRefBase::PreprocessorOpts
std::shared_ptr< PreprocessorOptions > PreprocessorOpts
Options controlling the preprocessor (aside from #include handling).
Definition: CompilerInvocation.h:92
makeBooleanOptionNormalizer
static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue, OptSpecifier OtherOpt)
Definition: CompilerInvocation.cpp:221
clang::CompilerInvocationValueBase::getFrontendOpts
FrontendOptions & getFrontendOpts()
Definition: CompilerInvocation.h:176
clang::AnalysisDiagClients
AnalysisDiagClients
AnalysisDiagClients - Set of available diagnostic clients for rendering analysis results.
Definition: AnalyzerOptions.h:45
clang::SanitizerSet
Definition: Sanitizers.h:153
clang::driver::getDriverOptTable
const llvm::opt::OptTable & getDriverOptTable()
Definition: DriverOptions.cpp:42
clang::codegenoptions::LocTrackingOnly
@ LocTrackingOnly
Emit location information but do not generate debug info in the output.
Definition: DebugInfoOptions.h:28
clang::LangStandard::getName
const char * getName() const
getName - Get the name of this standard.
Definition: LangStandard.h:83
Options.h
GeneratePreprocessorOutputArgs
static void GeneratePreprocessorOutputArgs(const PreprocessorOutputOptions &Opts, SmallVectorImpl< const char * > &Args, CompilerInvocation::StringAllocator SA, frontend::ActionKind Action)
Definition: CompilerInvocation.cpp:4272
clang::frontend::ObjCXXSystem
@ ObjCXXSystem
Like System, but only used for ObjC++.
Definition: HeaderSearchOptions.h:58
clang::LangOptions::ObjCRuntime
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:397
clang::frontend::EmitObj
@ EmitObj
Emit a .o file.
Definition: FrontendOptions.h:76
clang::PreprocessorOutputOptions
PreprocessorOutputOptions - Options for controlling the C preprocessor output (e.g....
Definition: PreprocessorOutputOptions.h:16
clang::FrontendOptions::getInputKindForExtension
static InputKind getInputKindForExtension(StringRef Extension)
getInputKindForExtension - Return the appropriate input kind for a file extension.
Definition: FrontendOptions.cpp:15
HeaderSearchOptions.h
clang::frontend::ActionKind
ActionKind
Definition: FrontendOptions.h:35
CodeCompleteOptions.h
clang::LangOptions::OMPTargetTriples
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:436
clang::CodeGenOptions::CmdArgs
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
Definition: CodeGenOptions.h:356
clang::CodeGenOptions::DebugPrefixMap
std::map< std::string, std::string > DebugPrefixMap
Definition: CodeGenOptions.h:183
clang::CodeGenOptions::ProfileNone
@ ProfileNone
Definition: CodeGenOptions.h:86
FrontendOptions.h
clang::FrontendOptions::OutputFile
std::string OutputFile
The output file, if any.
Definition: FrontendOptions.h:433
clang::XRayInstrKind::None
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
clang::CodeGenOptions::MemoryProfileOutput
std::string MemoryProfileOutput
Name of the profile file to use as output for with -fmemory-profile.
Definition: CodeGenOptions.h:254
clang::FrontendOptions::AuxTriple
std::string AuxTriple
Auxiliary triple for CUDA/HIP compilation.
Definition: FrontendOptions.h:488
clang::TargetCXXABI::getKind
Kind getKind() const
Definition: TargetCXXABI.h:82
clang::ObjCRuntime::allowsARC
bool allowsARC() const
Does this runtime allow ARC at all?
Definition: ObjCRuntime.h:142
clang::HeaderSearchOptions::Sysroot
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
Definition: HeaderSearchOptions.h:100
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:90
clang::CompilerInvocationRefBase::HeaderSearchOpts
std::shared_ptr< HeaderSearchOptions > HeaderSearchOpts
Options controlling the #include directive.
Definition: CompilerInvocation.h:89
clang::PreprocessorOptions::ChainedIncludes
std::vector< std::string > ChainedIncludes
Headers that will be converted to chained PCHs in memory.
Definition: PreprocessorOptions.h:100
clang::frontend::ParseSyntaxOnly
@ ParseSyntaxOnly
Parse and perform semantic analysis.
Definition: FrontendOptions.h:112
clang::AnalyzerOptions::InliningMode
AnalysisInliningMode InliningMode
The mode of function selection used during inlining.
Definition: AnalyzerOptions.h:251
Version.h
LangOptions.h
llvm::opt
Definition: DiagnosticOptions.h:19
Std
LangStandard::Kind Std
Definition: InterpolatingCompilationDatabase.cpp:134
Diagnostic.h
DriverDiagnostic.h
clang::ASTDumpOutputFormat
ASTDumpOutputFormat
Used to specify the format for printing AST dump information.
Definition: ASTDumperUtils.h:21
clang::FrontendOptions
FrontendOptions - Options for controlling the behavior of the frontend.
Definition: FrontendOptions.h:268
clang::CompilerInvocationValueBase::DependencyOutputOpts
DependencyOutputOptions DependencyOutputOpts
Options controlling dependency output.
Definition: CompilerInvocation.h:144
Utils.h
clang::isLetter
LLVM_READONLY bool isLetter(unsigned char c)
Return true if this character is an ASCII letter: [a-zA-Z].
Definition: CharInfo.h:117
clang::frontend::ASTDeclList
@ ASTDeclList
Parse ASTs and list Decl nodes.
Definition: FrontendOptions.h:37
ParseFileSystemArgs
static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args, DiagnosticsEngine &Diags)
Definition: CompilerInvocation.cpp:2172
clang::CodeGenOptions::OptimizationRemarkMissed
OptRemark OptimizationRemarkMissed
Selected optimizations for which we should enable missed optimization remarks.
Definition: CodeGenOptions.h:336
clang::InputKind::isUnknown
bool isUnknown() const
Is the input kind fully-unknown?
Definition: FrontendOptions.h:192
clang::InputKind::HeaderUnit_Abs
@ HeaderUnit_Abs
Definition: FrontendOptions.h:174
clang::AnalyzerOptions::AnalysisDiagOpt
AnalysisDiagClients AnalysisDiagOpt
Definition: AnalyzerOptions.h:197
clang::CompilerInvocationRefBase::AnalyzerOpts
AnalyzerOptionsRef AnalyzerOpts
Options controlling the static analyzer.
Definition: CompilerInvocation.h:95
clang::InputKind::getHeader
InputKind getHeader() const
Definition: FrontendOptions.h:204
clang::frontend::DumpRawTokens
@ DumpRawTokens
Dump out raw tokens.
Definition: FrontendOptions.h:52
clang::CodeGenOptions::ProfileClangInstr
@ ProfileClangInstr
Definition: CodeGenOptions.h:87
clang::LangOptions::ModuleFeatures
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
Definition: LangOptions.h:423
clang::InputKind::getLanguage
Language getLanguage() const
Definition: FrontendOptions.h:182
clang::frontend::EmitLLVM
@ EmitLLVM
Emit a .ll file.
Definition: FrontendOptions.h:67
clang::PreprocessorOutputOptions::DirectivesOnly
unsigned DirectivesOnly
Process directives but do not expand macros.
Definition: PreprocessorOutputOptions.h:28
DependencyOutputOptions.h
clang::DependencyOutputOptions::ShowIncludesDest
ShowIncludesDestination ShowIncludesDest
Destination of cl.exe style /showIncludes info.
Definition: DependencyOutputOptions.h:48
clang::HeaderSearchOptions::ModuleFormat
std::string ModuleFormat
The module/pch container format.
Definition: HeaderSearchOptions.h:125
clang::InputKind::Precompiled
@ Precompiled
Definition: FrontendOptions.h:164
clang::LangOptions::NoBuiltinFuncs
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
Definition: LangOptions.h:429
clang::FrontendOptions::ASTDumpAll
unsigned ASTDumpAll
Whether we deserialize all decls when forming AST dumps.
Definition: FrontendOptions.h:321
clang::InputKind::getPreprocessed
InputKind getPreprocessed() const
Definition: FrontendOptions.h:199
clang::CodeGenOptions::OptRemark
Optimization remark with an optional regular expression pattern.
Definition: CodeGenOptions.h:308
llvm::SmallString< 128 >
clang::FrontendOptions::ObjCMTAction
unsigned ObjCMTAction
Definition: FrontendOptions.h:415
bool
#define bool
Definition: stdbool.h:20
clang::Language::C
@ C
Languages that the frontend can parse and compile.
clang::CodeGenOptions::OptRecordFormat
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
Definition: CodeGenOptions.h:292
clang::CompilerInvocationRefBase::getLangOpts
LangOptions * getLangOpts()
Definition: CompilerInvocation.h:104
clang::frontend::Quoted
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
Definition: HeaderSearchOptions.h:34
TextDiagnosticBuffer.h
clang::frontend::PrintDependencyDirectivesSourceMinimizerOutput
@ PrintDependencyDirectivesSourceMinimizerOutput
Print the output of the dependency directives source minimizer.
Definition: FrontendOptions.h:145
clang::getClangFullRepositoryVersion
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:60
clang::TargetCXXABI::isABI
static bool isABI(StringRef Name)
Definition: TargetCXXABI.h:63
clang::DiagnosticOptions::DefaultTabStop
@ DefaultTabStop
Definition: DiagnosticOptions.h:81
clang::LangOptions::SYCL_Default
@ SYCL_Default
Definition: LangOptions.h:160
clang::PreprocessorOptions::UsePredefines
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
Definition: PreprocessorOptions.h:73
GenerateTargetArgs
static void GenerateTargetArgs(const TargetOptions &Opts, SmallVectorImpl< const char * > &Args, CompilerInvocation::StringAllocator SA)
Definition: CompilerInvocation.cpp:4322
clang::frontend::EmitHTML
@ EmitHTML
Translate input source into HTML.
Definition: FrontendOptions.h:64
clang::CXXABI
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:29
clang::FrontendOptions::DashX
InputKind DashX
The input kind, either specified via -x argument or deduced from the input file name.
Definition: FrontendOptions.h:423
clang::HeaderSearchOptions::UseLibcxx
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
Definition: HeaderSearchOptions.h:197
clang::DiagnosticsEngine::getNumWarnings
unsigned getNumWarnings() const
Definition: Diagnostic.h:852
clang::HeaderSearchOptions::PrebuiltModulePaths
std::vector< std::string > PrebuiltModulePaths
The directories used to load prebuilt module files.
Definition: HeaderSearchOptions.h:122
clang::frontend::RewriteMacros
@ RewriteMacros
Expand macros but not #includes.
Definition: FrontendOptions.h:124
clang::AnalysisConstraints
AnalysisConstraints
AnalysisConstraints - Set of available constraint models.
Definition: AnalyzerOptions.h:37
clang::LangOptions::HybridGC
@ HybridGC
Definition: LangOptions.h:83
clang::FrontendOptions::UseGlobalModuleIndex
unsigned UseGlobalModuleIndex
Whether we can use the global module index if available.
Definition: FrontendOptions.h:312
CXXABI
#define CXXABI(Name, Str)
Definition: TargetCXXABI.h:32
clang::LangOptions::DCC_VectorCall
@ DCC_VectorCall
Definition: LangOptions.h:134
denormalizeString
static void denormalizeString(SmallVectorImpl< const char * > &Args, const char *Spelling, CompilerInvocation::StringAllocator SA, Option::OptionClass OptClass, unsigned TableIndex, T Value)
Definition: CompilerInvocation.cpp:266
clang::AnalyzerOptions::getRegisteredCheckers
static std::vector< StringRef > getRegisteredCheckers(bool IncludeExperimental=false)
Retrieves the list of checkers generated from Checkers.td.
Definition: AnalyzerOptions.h:402
clang::HeaderSearchOptions::UseStandardCXXIncludes
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
Definition: HeaderSearchOptions.h:194
clang::CompilerInvocation::generateCC1CommandLine
void generateCC1CommandLine(llvm::SmallVectorImpl< const char * > &Args, StringAllocator SA) const
Generate a cc1-compatible command line arguments from this instance.
Definition: CompilerInvocation.cpp:4601
clang::LangOptions::ClangABI::Ver4
@ Ver4
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
clang::FrontendOptions::ARCMT_None
@ ARCMT_None
Definition: FrontendOptions.h:356
clang::CompilerInvocationRefBase::~CompilerInvocationRefBase
~CompilerInvocationRefBase()
clang::CompilerInvocationRefBase::getAnalyzerOpts
AnalyzerOptionsRef getAnalyzerOpts() const
Definition: CompilerInvocation.h:132
clang::CodeGenOptions
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
Definition: CodeGenOptions.h:49
clang::NUM_ANALYSIS_DIAG_CLIENTS
@ NUM_ANALYSIS_DIAG_CLIENTS
Definition: AnalyzerOptions.h:49
clang::CodeGenOptions::CoverageVersion
char CoverageVersion[4]
The version string to put into coverage files.
Definition: CodeGenOptions.h:164
clang::HeaderSearchOptions::PrebuiltModuleFiles
std::map< std::string, std::string, std::less<> > PrebuiltModuleFiles
The mapping of module names to prebuilt module files.
Definition: HeaderSearchOptions.h:119
clang::AnalyzerOptions::isUnknownAnalyzerConfig
bool isUnknownAnalyzerConfig(StringRef Name) const
Definition: AnalyzerOptions.h:280
clang::serialization::VERSION_MINOR
const unsigned VERSION_MINOR
AST file minor version number supported by this version of Clang.
Definition: ASTBitCodes.h:54
clang::AnalyzerOptions::CheckersAndPackages
std::vector< std::pair< std::string, bool > > CheckersAndPackages
Pairs of checker/package name and enable/disable.
Definition: AnalyzerOptions.h:188
clang::ModuleMap
Definition: ModuleMap.h:75
clang::codegenoptions::DebugTemplateNamesKind::Full
@ Full
clang::CodeGenOptions::SRCK_InRegs
@ SRCK_InRegs
Definition: CodeGenOptions.h:82
clang::parseXRayInstrValue
XRayInstrMask parseXRayInstrValue(StringRef Value)
Parses a command line argument into a mask.
Definition: XRayInstr.cpp:19
clang::InputKind::getFormat
Format getFormat() const
Definition: FrontendOptions.h:183
clang::ShowIncludesDestination::Stderr
@ Stderr
denormalizeStringImpl
static void denormalizeStringImpl(SmallVectorImpl< const char * > &Args, const char *Spelling, CompilerInvocation::StringAllocator SA, Option::OptionClass OptClass, unsigned, const Twine &Value)
Definition: CompilerInvocation.cpp:242
clang::CodeGenOptions::XRayInstrumentationBundle
XRayInstrSet XRayInstrumentationBundle
Set of XRay instrumentation kinds to emit.
Definition: CodeGenOptions.h:369
clang::LangOptions::Sanitize
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:368
clang::FrontendOptions::ModuleFileExtensions
std::vector< std::shared_ptr< ModuleFileExtension > > ModuleFileExtensions
The list of module file extensions.
Definition: FrontendOptions.h:464
clang::frontend::Angled
@ Angled
Paths for '#include <>' added by '-I'.
Definition: HeaderSearchOptions.h:37
IsHeaderFile
static bool IsHeaderFile(const std::string &Filename)
Definition: RewriteModernObjC.cpp:629
ParseHeaderSearchArgs
static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, const std::string &WorkingDir)
Definition: CompilerInvocation.cpp:3033
clang::CodeGenOptions::RK_Disabled
@ RK_Disabled
Definition: CodeGenOptions.h:302
clang::InputKind::ModuleMap
@ ModuleMap
Definition: FrontendOptions.h:163
clang::AnalyzerOptions::Config
ConfigTable Config
A key-value table of use-specified configuration values.
Definition: AnalyzerOptions.h:195
ASTBitCodes.h
clang::AnalysisInliningMode
AnalysisInliningMode
AnalysisInlineFunctionSelection - Set of inlining function selection heuristics.
Definition: AnalyzerOptions.h:60
clang::CompilerInvocationRefBase::getPreprocessorOpts
PreprocessorOptions & getPreprocessorOpts()
Definition: CompilerInvocation.h:126
clang::frontend::EmitBC
@ EmitBC
Emit a .bc file.
Definition: FrontendOptions.h:61
clang::frontend::GenerateHeaderUnit
@ GenerateHeaderUnit
Generate a C++20 header unit module from a header file.
Definition: FrontendOptions.h:94
clang::LangOptions::UseTargetPathSeparator
bool UseTargetPathSeparator
Indicates whether the FILE macro should use the target's platform-specific file separator or whether ...
Definition: LangOptions.h:468
clang::CompilerInvocationValueBase::PreprocessorOutputOpts
PreprocessorOutputOptions PreprocessorOutputOpts
Options controlling preprocessed output.
Definition: CompilerInvocation.h:153
SourceLocation.h
P
StringRef P
Definition: ASTMatchersInternal.cpp:563
clang::TargetCXXABI::isSupportedCXXABI
static bool isSupportedCXXABI(const llvm::Triple &T, Kind Kind)
Definition: TargetCXXABI.h:89
clang::CodeGenOptions::OptRemark::hasValidPattern
bool hasValidPattern() const
Returns true iff the optimization remark holds a valid regular expression.
Definition: CodeGenOptions.h:318
GenerateHeaderSearchArgs
static void GenerateHeaderSearchArgs(HeaderSearchOptions &Opts, SmallVectorImpl< const char * > &Args, CompilerInvocation::StringAllocator SA)
Definition: CompilerInvocation.cpp:2907
clang::serialized_diags::create
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
Definition: SerializedDiagnosticPrinter.cpp:301
setPGOUseInstrumentor
static void setPGOUseInstrumentor(CodeGenOptions &Opts, const Twine &ProfileName)
Definition: CompilerInvocation.cpp:1299
parseDiagnosticLevelMask
static bool parseDiagnosticLevelMask(StringRef FlagName, const std::vector< std::string > &Levels, DiagnosticsEngine &Diags, DiagnosticLevelMask &M)
Definition: CompilerInvocation.cpp:1230
clang::serializeSanitizerSet
void serializeSanitizerSet(SanitizerSet Set, SmallVectorImpl< StringRef > &Values)
Serialize a SanitizerSet into values for -fsanitize= or -fno-sanitize=.
Definition: Sanitizers.cpp:39
CharInfo.h
clang::HeaderSearchOptions::ModulesIgnoreMacros
llvm::SmallSetVector< llvm::CachedHashString, 16 > ModulesIgnoreMacros
The set of macro names that should be ignored for the purposes of computing the module hash.
Definition: HeaderSearchOptions.h:182
clang::NumInliningModes
@ NumInliningModes
Definition: AnalyzerOptions.h:63
clang::DiagnosticOptions::Warnings
std::vector< std::string > Warnings
The list of -W...
Definition: DiagnosticOptions.h:111
clang::codegenoptions::FullDebugInfo
@ FullDebugInfo
Generate complete debug info.
Definition: DebugInfoOptions.h:44
clang::HeaderSearchOptions::ModuleUserBuildPath
std::string ModuleUserBuildPath
The directory used for a user build.
Definition: HeaderSearchOptions.h:116
clang::Language
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
clang::ObjCRuntime::getAsString
std::string getAsString() const
Definition: ObjCRuntime.cpp:23
clang::FrontendOptions::IsSystemModule
unsigned IsSystemModule
When using -emit-module, treat the modulemap as a system module.
Definition: FrontendOptions.h:345
clang::LangOptions::NoSanitizeFiles
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
Definition: LangOptions.h:374
clang::CompilerInvocation::getModuleHash
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
Definition: CompilerInvocation.cpp:4505
clang::EDK_DepFileEntry
@ EDK_DepFileEntry
Definition: DependencyOutputOptions.h:28
clang::HeaderSearchOptions::AddPath
void AddPath(StringRef Path, frontend::IncludeDirGroup Group, bool IsFramework, bool IgnoreSysRoot)
AddPath - Add the Path path to the specified Group list.
Definition: HeaderSearchOptions.h:241
LangStandard.h
clang::PreprocessorOptions::addMacroDef
void addMacroDef(StringRef Name)
Definition: PreprocessorOptions.h:226
clang::frontend::GenerateModule
@ GenerateModule
Generate pre-compiled module from a module map.
Definition: FrontendOptions.h:85
clang::LangOptions::NonGC
@ NonGC