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