clang  9.0.0svn
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"
19 #include "clang/Basic/LLVM.h"
22 #include "clang/Basic/Sanitizers.h"
25 #include "clang/Basic/Version.h"
26 #include "clang/Basic/Visibility.h"
27 #include "clang/Basic/XRayInstr.h"
28 #include "clang/Config/config.h"
29 #include "clang/Driver/Driver.h"
31 #include "clang/Driver/Options.h"
40 #include "clang/Frontend/Utils.h"
46 #include "llvm/ADT/APInt.h"
47 #include "llvm/ADT/ArrayRef.h"
48 #include "llvm/ADT/CachedHashString.h"
49 #include "llvm/ADT/Hashing.h"
50 #include "llvm/ADT/None.h"
51 #include "llvm/ADT/Optional.h"
52 #include "llvm/ADT/SmallString.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringRef.h"
55 #include "llvm/ADT/StringSwitch.h"
56 #include "llvm/ADT/Triple.h"
57 #include "llvm/ADT/Twine.h"
58 #include "llvm/IR/DebugInfoMetadata.h"
59 #include "llvm/Linker/Linker.h"
60 #include "llvm/MC/MCTargetOptions.h"
61 #include "llvm/Option/Arg.h"
62 #include "llvm/Option/ArgList.h"
63 #include "llvm/Option/OptSpecifier.h"
64 #include "llvm/Option/OptTable.h"
65 #include "llvm/Option/Option.h"
66 #include "llvm/ProfileData/InstrProfReader.h"
67 #include "llvm/Support/CodeGen.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/Error.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/ErrorOr.h"
72 #include "llvm/Support/FileSystem.h"
73 #include "llvm/Support/Host.h"
74 #include "llvm/Support/MathExtras.h"
75 #include "llvm/Support/MemoryBuffer.h"
76 #include "llvm/Support/Path.h"
77 #include "llvm/Support/Process.h"
78 #include "llvm/Support/Regex.h"
79 #include "llvm/Support/VersionTuple.h"
80 #include "llvm/Support/VirtualFileSystem.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/Target/TargetOptions.h"
83 #include <algorithm>
84 #include <atomic>
85 #include <cassert>
86 #include <cstddef>
87 #include <cstring>
88 #include <memory>
89 #include <string>
90 #include <tuple>
91 #include <utility>
92 #include <vector>
93 
94 using namespace clang;
95 using namespace driver;
96 using namespace options;
97 using namespace llvm::opt;
98 
99 //===----------------------------------------------------------------------===//
100 // Initialization.
101 //===----------------------------------------------------------------------===//
102 
104  : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
105  DiagnosticOpts(new DiagnosticOptions()),
106  HeaderSearchOpts(new HeaderSearchOptions()),
107  PreprocessorOpts(new PreprocessorOptions()) {}
108 
110  : LangOpts(new LangOptions(*X.getLangOpts())),
115 
117 
118 //===----------------------------------------------------------------------===//
119 // Deserialization (from args)
120 //===----------------------------------------------------------------------===//
121 
122 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
123  DiagnosticsEngine &Diags) {
124  unsigned DefaultOpt = llvm::CodeGenOpt::None;
125  if (IK.getLanguage() == InputKind::OpenCL && !Args.hasArg(OPT_cl_opt_disable))
126  DefaultOpt = llvm::CodeGenOpt::Default;
127 
128  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
129  if (A->getOption().matches(options::OPT_O0))
130  return llvm::CodeGenOpt::None;
131 
132  if (A->getOption().matches(options::OPT_Ofast))
133  return llvm::CodeGenOpt::Aggressive;
134 
135  assert(A->getOption().matches(options::OPT_O));
136 
137  StringRef S(A->getValue());
138  if (S == "s" || S == "z" || S.empty())
139  return llvm::CodeGenOpt::Default;
140 
141  if (S == "g")
142  return llvm::CodeGenOpt::Less;
143 
144  return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
145  }
146 
147  return DefaultOpt;
148 }
149 
150 static unsigned getOptimizationLevelSize(ArgList &Args) {
151  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
152  if (A->getOption().matches(options::OPT_O)) {
153  switch (A->getValue()[0]) {
154  default:
155  return 0;
156  case 's':
157  return 1;
158  case 'z':
159  return 2;
160  }
161  }
162  }
163  return 0;
164 }
165 
166 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
167  OptSpecifier GroupWithValue,
168  std::vector<std::string> &Diagnostics) {
169  for (auto *A : Args.filtered(Group)) {
170  if (A->getOption().getKind() == Option::FlagClass) {
171  // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
172  // its name (minus the "W" or "R" at the beginning) to the warning list.
173  Diagnostics.push_back(A->getOption().getName().drop_front(1));
174  } else if (A->getOption().matches(GroupWithValue)) {
175  // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group.
176  Diagnostics.push_back(A->getOption().getName().drop_front(1).rtrim("=-"));
177  } else {
178  // Otherwise, add its value (for OPT_W_Joined and similar).
179  for (const auto *Arg : A->getValues())
180  Diagnostics.emplace_back(Arg);
181  }
182  }
183 }
184 
185 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
186 // it won't verify the input.
187 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
188  DiagnosticsEngine *Diags);
189 
190 static void getAllNoBuiltinFuncValues(ArgList &Args,
191  std::vector<std::string> &Funcs) {
193  for (const auto &Arg : Args) {
194  const Option &O = Arg->getOption();
195  if (O.matches(options::OPT_fno_builtin_)) {
196  const char *FuncName = Arg->getValue();
197  if (Builtin::Context::isBuiltinFunc(FuncName))
198  Values.push_back(FuncName);
199  }
200  }
201  Funcs.insert(Funcs.end(), Values.begin(), Values.end());
202 }
203 
204 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
205  DiagnosticsEngine &Diags) {
206  bool Success = true;
207  if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
208  StringRef Name = A->getValue();
209  AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
210 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
211  .Case(CMDFLAG, NAME##Model)
212 #include "clang/StaticAnalyzer/Core/Analyses.def"
213  .Default(NumStores);
214  if (Value == NumStores) {
215  Diags.Report(diag::err_drv_invalid_value)
216  << A->getAsString(Args) << Name;
217  Success = false;
218  } else {
219  Opts.AnalysisStoreOpt = Value;
220  }
221  }
222 
223  if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
224  StringRef Name = A->getValue();
225  AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
226 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
227  .Case(CMDFLAG, NAME##Model)
228 #include "clang/StaticAnalyzer/Core/Analyses.def"
229  .Default(NumConstraints);
230  if (Value == NumConstraints) {
231  Diags.Report(diag::err_drv_invalid_value)
232  << A->getAsString(Args) << Name;
233  Success = false;
234  } else {
236  }
237  }
238 
239  if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
240  StringRef Name = A->getValue();
241  AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
242 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
243  .Case(CMDFLAG, PD_##NAME)
244 #include "clang/StaticAnalyzer/Core/Analyses.def"
245  .Default(NUM_ANALYSIS_DIAG_CLIENTS);
246  if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
247  Diags.Report(diag::err_drv_invalid_value)
248  << A->getAsString(Args) << Name;
249  Success = false;
250  } else {
251  Opts.AnalysisDiagOpt = Value;
252  }
253  }
254 
255  if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
256  StringRef Name = A->getValue();
257  AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
258 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
259  .Case(CMDFLAG, NAME)
260 #include "clang/StaticAnalyzer/Core/Analyses.def"
261  .Default(NumPurgeModes);
262  if (Value == NumPurgeModes) {
263  Diags.Report(diag::err_drv_invalid_value)
264  << A->getAsString(Args) << Name;
265  Success = false;
266  } else {
267  Opts.AnalysisPurgeOpt = Value;
268  }
269  }
270 
271  if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
272  StringRef Name = A->getValue();
273  AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
274 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
275  .Case(CMDFLAG, NAME)
276 #include "clang/StaticAnalyzer/Core/Analyses.def"
277  .Default(NumInliningModes);
278  if (Value == NumInliningModes) {
279  Diags.Report(diag::err_drv_invalid_value)
280  << A->getAsString(Args) << Name;
281  Success = false;
282  } else {
283  Opts.InliningMode = Value;
284  }
285  }
286 
287  Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
288  Opts.ShowCheckerHelpAlpha = Args.hasArg(OPT_analyzer_checker_help_alpha);
290  Args.hasArg(OPT_analyzer_checker_help_developer);
291 
292  Opts.ShowCheckerOptionList = Args.hasArg(OPT_analyzer_checker_option_help);
294  Args.hasArg(OPT_analyzer_checker_option_help_alpha);
296  Args.hasArg(OPT_analyzer_checker_option_help_developer);
297 
298  Opts.ShowConfigOptionsList = Args.hasArg(OPT_analyzer_config_help);
299  Opts.ShowEnabledCheckerList = Args.hasArg(OPT_analyzer_list_enabled_checkers);
301  /* negated */!llvm::StringSwitch<bool>(
302  Args.getLastArgValue(OPT_analyzer_config_compatibility_mode))
303  .Case("true", true)
304  .Case("false", false)
305  .Default(false);
306  Opts.DisableAllChecks = Args.hasArg(OPT_analyzer_disable_all_checks);
307 
309  Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
310  Opts.DumpExplodedGraphTo = Args.getLastArgValue(OPT_analyzer_dump_egraph);
311  Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
312  Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
313  Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
314  Opts.AnalyzeNestedBlocks =
315  Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
316  Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function);
317  Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
318  Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
319  Opts.maxBlockVisitOnPath =
320  getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags);
321  Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
322  Opts.InlineMaxStackDepth =
323  getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
324  Opts.InlineMaxStackDepth, Diags);
325 
326  Opts.CheckersControlList.clear();
327  for (const Arg *A :
328  Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
329  A->claim();
330  bool enable = (A->getOption().getID() == OPT_analyzer_checker);
331  // We can have a list of comma separated checker names, e.g:
332  // '-analyzer-checker=cocoa,unix'
333  StringRef checkerList = A->getValue();
334  SmallVector<StringRef, 4> checkers;
335  checkerList.split(checkers, ",");
336  for (auto checker : checkers)
337  Opts.CheckersControlList.emplace_back(checker, enable);
338  }
339 
340  // Go through the analyzer configuration options.
341  for (const auto *A : Args.filtered(OPT_analyzer_config)) {
342 
343  // We can have a list of comma separated config names, e.g:
344  // '-analyzer-config key1=val1,key2=val2'
345  StringRef configList = A->getValue();
346  SmallVector<StringRef, 4> configVals;
347  configList.split(configVals, ",");
348  for (const auto &configVal : configVals) {
349  StringRef key, val;
350  std::tie(key, val) = configVal.split("=");
351  if (val.empty()) {
352  Diags.Report(SourceLocation(),
353  diag::err_analyzer_config_no_value) << configVal;
354  Success = false;
355  break;
356  }
357  if (val.find('=') != StringRef::npos) {
358  Diags.Report(SourceLocation(),
359  diag::err_analyzer_config_multiple_values)
360  << configVal;
361  Success = false;
362  break;
363  }
364 
365  // TODO: Check checker options too, possibly in CheckerRegistry.
366  // Leave unknown non-checker configs unclaimed.
367  if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
369  Diags.Report(diag::err_analyzer_config_unknown) << key;
370  continue;
371  }
372 
373  A->claim();
374  Opts.Config[key] = val;
375  }
376  }
377 
379  parseAnalyzerConfigs(Opts, &Diags);
380  else
381  parseAnalyzerConfigs(Opts, nullptr);
382 
383  llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
384  for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
385  if (i != 0)
386  os << " ";
387  os << Args.getArgString(i);
388  }
389  os.flush();
390 
391  return Success;
392 }
393 
395  StringRef OptionName, StringRef DefaultVal) {
396  return Config.insert({OptionName, DefaultVal}).first->second;
397 }
398 
400  DiagnosticsEngine *Diags,
401  StringRef &OptionField, StringRef Name,
402  StringRef DefaultVal) {
403  // String options may be known to invalid (e.g. if the expected string is a
404  // file name, but the file does not exist), those will have to be checked in
405  // parseConfigs.
406  OptionField = getStringOption(Config, Name, DefaultVal);
407 }
408 
410  DiagnosticsEngine *Diags,
411  bool &OptionField, StringRef Name, bool DefaultVal) {
412  auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>(
413  getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
414  .Case("true", true)
415  .Case("false", false)
416  .Default(None);
417 
418  if (!PossiblyInvalidVal) {
419  if (Diags)
420  Diags->Report(diag::err_analyzer_config_invalid_input)
421  << Name << "a boolean";
422  else
423  OptionField = DefaultVal;
424  } else
425  OptionField = PossiblyInvalidVal.getValue();
426 }
427 
429  DiagnosticsEngine *Diags,
430  unsigned &OptionField, StringRef Name,
431  unsigned DefaultVal) {
432 
433  OptionField = DefaultVal;
434  bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
435  .getAsInteger(0, OptionField);
436  if (Diags && HasFailed)
437  Diags->Report(diag::err_analyzer_config_invalid_input)
438  << Name << "an unsigned";
439 }
440 
442  DiagnosticsEngine *Diags) {
443  // TODO: There's no need to store the entire configtable, it'd be plenty
444  // enough tostore checker options.
445 
446 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
447  initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
448 
449 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
450  SHALLOW_VAL, DEEP_VAL) \
451  switch (AnOpts.getUserMode()) { \
452  case UMK_Shallow: \
453  initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL); \
454  break; \
455  case UMK_Deep: \
456  initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL); \
457  break; \
458  } \
459 
460 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
461 #undef ANALYZER_OPTION
462 #undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
463 
464  // At this point, AnalyzerOptions is configured. Let's validate some options.
465 
466  if (!Diags)
467  return;
468 
469  if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
470  Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
471  << "a filename";
472 
473  if (!AnOpts.ModelPath.empty() &&
474  !llvm::sys::fs::is_directory(AnOpts.ModelPath))
475  Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
476  << "a filename";
477 }
478 
479 static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
480  Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error);
481  Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal);
482  return true;
483 }
484 
485 static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
486  Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
487  Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
488 }
489 
490 static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags) {
491  if (Arg *A = Args.getLastArg(OPT_mcode_model)) {
492  StringRef Value = A->getValue();
493  if (Value == "small" || Value == "kernel" || Value == "medium" ||
494  Value == "large" || Value == "tiny")
495  return Value;
496  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
497  }
498  return "default";
499 }
500 
501 static llvm::Reloc::Model getRelocModel(ArgList &Args,
502  DiagnosticsEngine &Diags) {
503  if (Arg *A = Args.getLastArg(OPT_mrelocation_model)) {
504  StringRef Value = A->getValue();
505  auto RM = llvm::StringSwitch<llvm::Optional<llvm::Reloc::Model>>(Value)
506  .Case("static", llvm::Reloc::Static)
507  .Case("pic", llvm::Reloc::PIC_)
508  .Case("ropi", llvm::Reloc::ROPI)
509  .Case("rwpi", llvm::Reloc::RWPI)
510  .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
511  .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC)
512  .Default(None);
513  if (RM.hasValue())
514  return *RM;
515  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
516  }
517  return llvm::Reloc::PIC_;
518 }
519 
520 /// Create a new Regex instance out of the string value in \p RpassArg.
521 /// It returns a pointer to the newly generated Regex instance.
522 static std::shared_ptr<llvm::Regex>
524  Arg *RpassArg) {
525  StringRef Val = RpassArg->getValue();
526  std::string RegexError;
527  std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val);
528  if (!Pattern->isValid(RegexError)) {
529  Diags.Report(diag::err_drv_optimization_remark_pattern)
530  << RegexError << RpassArg->getAsString(Args);
531  Pattern.reset();
532  }
533  return Pattern;
534 }
535 
536 static bool parseDiagnosticLevelMask(StringRef FlagName,
537  const std::vector<std::string> &Levels,
538  DiagnosticsEngine *Diags,
539  DiagnosticLevelMask &M) {
540  bool Success = true;
541  for (const auto &Level : Levels) {
542  DiagnosticLevelMask const PM =
543  llvm::StringSwitch<DiagnosticLevelMask>(Level)
544  .Case("note", DiagnosticLevelMask::Note)
545  .Case("remark", DiagnosticLevelMask::Remark)
546  .Case("warning", DiagnosticLevelMask::Warning)
547  .Case("error", DiagnosticLevelMask::Error)
548  .Default(DiagnosticLevelMask::None);
549  if (PM == DiagnosticLevelMask::None) {
550  Success = false;
551  if (Diags)
552  Diags->Report(diag::err_drv_invalid_value) << FlagName << Level;
553  }
554  M = M | PM;
555  }
556  return Success;
557 }
558 
559 static void parseSanitizerKinds(StringRef FlagName,
560  const std::vector<std::string> &Sanitizers,
561  DiagnosticsEngine &Diags, SanitizerSet &S) {
562  for (const auto &Sanitizer : Sanitizers) {
563  SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
564  if (K == SanitizerMask())
565  Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
566  else
567  S.set(K, true);
568  }
569 }
570 
571 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
572  ArgList &Args, DiagnosticsEngine &D,
573  XRayInstrSet &S) {
575  llvm::SplitString(Bundle, BundleParts, ",");
576  for (const auto B : BundleParts) {
577  auto Mask = parseXRayInstrValue(B);
578  if (Mask == XRayInstrKind::None)
579  if (B != "none")
580  D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
581  else
582  S.Mask = Mask;
583  else if (Mask == XRayInstrKind::All)
584  S.Mask = Mask;
585  else
586  S.set(Mask, true);
587  }
588 }
589 
590 // Set the profile kind for fprofile-instrument.
591 static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args,
592  DiagnosticsEngine &Diags) {
593  Arg *A = Args.getLastArg(OPT_fprofile_instrument_EQ);
594  if (A == nullptr)
595  return;
596  StringRef S = A->getValue();
597  unsigned I = llvm::StringSwitch<unsigned>(S)
598  .Case("none", CodeGenOptions::ProfileNone)
599  .Case("clang", CodeGenOptions::ProfileClangInstr)
600  .Case("llvm", CodeGenOptions::ProfileIRInstr)
601  .Case("csllvm", CodeGenOptions::ProfileCSIRInstr)
602  .Default(~0U);
603  if (I == ~0U) {
604  Diags.Report(diag::err_drv_invalid_pgo_instrumentor) << A->getAsString(Args)
605  << S;
606  return;
607  }
608  auto Instrumentor = static_cast<CodeGenOptions::ProfileInstrKind>(I);
609  Opts.setProfileInstr(Instrumentor);
610 }
611 
612 // Set the profile kind using fprofile-instrument-use-path.
614  const Twine &ProfileName) {
615  auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
616  // In error, return silently and let Clang PGOUse report the error message.
617  if (auto E = ReaderOrErr.takeError()) {
618  llvm::consumeError(std::move(E));
619  Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
620  return;
621  }
622  std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
623  std::move(ReaderOrErr.get());
624  if (PGOReader->isIRLevelProfile()) {
625  if (PGOReader->hasCSIRLevelProfile())
626  Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
627  else
628  Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
629  } else
630  Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
631 }
632 
633 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
634  DiagnosticsEngine &Diags,
635  const TargetOptions &TargetOpts,
636  const FrontendOptions &FrontendOpts) {
637  bool Success = true;
638  llvm::Triple Triple = llvm::Triple(TargetOpts.Triple);
639 
640  unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
641  // TODO: This could be done in Driver
642  unsigned MaxOptLevel = 3;
643  if (OptimizationLevel > MaxOptLevel) {
644  // If the optimization level is not supported, fall back on the default
645  // optimization
646  Diags.Report(diag::warn_drv_optimization_value)
647  << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
648  OptimizationLevel = MaxOptLevel;
649  }
650  Opts.OptimizationLevel = OptimizationLevel;
651 
652  // At O0 we want to fully disable inlining outside of cases marked with
653  // 'alwaysinline' that are required for correctness.
654  Opts.setInlining((Opts.OptimizationLevel == 0)
657  // Explicit inlining flags can disable some or all inlining even at
658  // optimization levels above zero.
659  if (Arg *InlineArg = Args.getLastArg(
660  options::OPT_finline_functions, options::OPT_finline_hint_functions,
661  options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
662  if (Opts.OptimizationLevel > 0) {
663  const Option &InlineOpt = InlineArg->getOption();
664  if (InlineOpt.matches(options::OPT_finline_functions))
665  Opts.setInlining(CodeGenOptions::NormalInlining);
666  else if (InlineOpt.matches(options::OPT_finline_hint_functions))
667  Opts.setInlining(CodeGenOptions::OnlyHintInlining);
668  else
669  Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
670  }
671  }
672 
673  Opts.ExperimentalNewPassManager = Args.hasFlag(
674  OPT_fexperimental_new_pass_manager, OPT_fno_experimental_new_pass_manager,
675  /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER);
676 
677  Opts.DebugPassManager =
678  Args.hasFlag(OPT_fdebug_pass_manager, OPT_fno_debug_pass_manager,
679  /* Default */ false);
680 
681  if (Arg *A = Args.getLastArg(OPT_fveclib)) {
682  StringRef Name = A->getValue();
683  if (Name == "Accelerate")
684  Opts.setVecLib(CodeGenOptions::Accelerate);
685  else if (Name == "SVML")
686  Opts.setVecLib(CodeGenOptions::SVML);
687  else if (Name == "none")
688  Opts.setVecLib(CodeGenOptions::NoLibrary);
689  else
690  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
691  }
692 
693  if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
694  unsigned Val =
695  llvm::StringSwitch<unsigned>(A->getValue())
696  .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
697  .Case("line-directives-only", codegenoptions::DebugDirectivesOnly)
698  .Case("limited", codegenoptions::LimitedDebugInfo)
699  .Case("standalone", codegenoptions::FullDebugInfo)
700  .Default(~0U);
701  if (Val == ~0U)
702  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
703  << A->getValue();
704  else
705  Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
706  }
707  if (Arg *A = Args.getLastArg(OPT_debugger_tuning_EQ)) {
708  unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
709  .Case("gdb", unsigned(llvm::DebuggerKind::GDB))
710  .Case("lldb", unsigned(llvm::DebuggerKind::LLDB))
711  .Case("sce", unsigned(llvm::DebuggerKind::SCE))
712  .Default(~0U);
713  if (Val == ~0U)
714  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
715  << A->getValue();
716  else
717  Opts.setDebuggerTuning(static_cast<llvm::DebuggerKind>(Val));
718  }
719  Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 0, Diags);
720  Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info);
721  Opts.EmitCodeView = Args.hasArg(OPT_gcodeview);
722  Opts.CodeViewGHash = Args.hasArg(OPT_gcodeview_ghash);
723  Opts.MacroDebugInfo = Args.hasArg(OPT_debug_info_macro);
724  Opts.WholeProgramVTables = Args.hasArg(OPT_fwhole_program_vtables);
725  Opts.LTOVisibilityPublicStd = Args.hasArg(OPT_flto_visibility_public_std);
726  Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
727  Opts.SplitDwarfInlining = !Args.hasArg(OPT_fno_split_dwarf_inlining);
728 
729  if (Arg *A =
730  Args.getLastArg(OPT_enable_split_dwarf, OPT_enable_split_dwarf_EQ)) {
731  if (A->getOption().matches(options::OPT_enable_split_dwarf)) {
732  Opts.setSplitDwarfMode(CodeGenOptions::SplitFileFission);
733  } else {
734  StringRef Name = A->getValue();
735  if (Name == "single")
736  Opts.setSplitDwarfMode(CodeGenOptions::SingleFileFission);
737  else if (Name == "split")
738  Opts.setSplitDwarfMode(CodeGenOptions::SplitFileFission);
739  else
740  Diags.Report(diag::err_drv_invalid_value)
741  << A->getAsString(Args) << Name;
742  }
743  }
744 
745  Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs);
746  Opts.DebugExplicitImport = Args.hasArg(OPT_dwarf_explicit_import);
747  Opts.DebugFwdTemplateParams = Args.hasArg(OPT_debug_forward_template_params);
748  Opts.EmbedSource = Args.hasArg(OPT_gembed_source);
749 
750  for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ))
751  Opts.DebugPrefixMap.insert(StringRef(Arg).split('='));
752 
753  if (const Arg *A =
754  Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists))
755  Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists;
756 
757  Opts.DisableLLVMPasses = Args.hasArg(OPT_disable_llvm_passes);
758  Opts.DisableLifetimeMarkers = Args.hasArg(OPT_disable_lifetimemarkers);
759  Opts.DisableO0ImplyOptNone = Args.hasArg(OPT_disable_O0_optnone);
760  Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
761  Opts.IndirectTlsSegRefs = Args.hasArg(OPT_mno_tls_direct_seg_refs);
762  Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
763  Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
764  OPT_fuse_register_sized_bitfield_access);
765  Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
766  Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa);
767  Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
768  Args.hasArg(OPT_new_struct_path_tbaa);
769  Opts.FineGrainedBitfieldAccesses =
770  Args.hasFlag(OPT_ffine_grained_bitfield_accesses,
771  OPT_fno_fine_grained_bitfield_accesses, false);
772  Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
773  Opts.RecordCommandLine = Args.getLastArgValue(OPT_record_command_line);
774  Opts.MergeAllConstants = Args.hasArg(OPT_fmerge_all_constants);
775  Opts.NoCommon = Args.hasArg(OPT_fno_common);
776  Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
777  Opts.OptimizeSize = getOptimizationLevelSize(Args);
778  Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
779  Args.hasArg(OPT_ffreestanding));
780  if (Opts.SimplifyLibCalls)
782  Opts.UnrollLoops =
783  Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
784  (Opts.OptimizationLevel > 1));
785  Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
786 
787  Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
788  Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
789  Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ);
790  Opts.DebugInfoForProfiling = Args.hasFlag(
791  OPT_fdebug_info_for_profiling, OPT_fno_debug_info_for_profiling, false);
792  Opts.DebugNameTable = static_cast<unsigned>(
793  Args.hasArg(OPT_ggnu_pubnames)
794  ? llvm::DICompileUnit::DebugNameTableKind::GNU
795  : Args.hasArg(OPT_gpubnames)
796  ? llvm::DICompileUnit::DebugNameTableKind::Default
798  Opts.DebugRangesBaseAddress = Args.hasArg(OPT_fdebug_ranges_base_address);
799 
800  setPGOInstrumentor(Opts, Args, Diags);
801  Opts.InstrProfileOutput =
802  Args.getLastArgValue(OPT_fprofile_instrument_path_EQ);
804  Args.getLastArgValue(OPT_fprofile_instrument_use_path_EQ);
805  if (!Opts.ProfileInstrumentUsePath.empty())
807  Opts.ProfileRemappingFile =
808  Args.getLastArgValue(OPT_fprofile_remapping_file_EQ);
809  if (!Opts.ProfileRemappingFile.empty() && !Opts.ExperimentalNewPassManager) {
810  Diags.Report(diag::err_drv_argument_only_allowed_with)
811  << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
812  << "-fexperimental-new-pass-manager";
813  }
814 
815  Opts.CoverageMapping =
816  Args.hasFlag(OPT_fcoverage_mapping, OPT_fno_coverage_mapping, false);
817  Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping);
818  Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose);
819  Opts.PreserveAsmComments = !Args.hasArg(OPT_fno_preserve_as_comments);
820  Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
821  Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
822  Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
823  Opts.RegisterGlobalDtorsWithAtExit =
824  Args.hasArg(OPT_fregister_global_dtors_with_atexit);
825  Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
826  Opts.CodeModel = TargetOpts.CodeModel;
827  Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass);
828  Opts.DisableFPElim =
829  (Args.hasArg(OPT_mdisable_fp_elim) || Args.hasArg(OPT_pg));
830  Opts.DisableFree = Args.hasArg(OPT_disable_free);
831  Opts.DiscardValueNames = Args.hasArg(OPT_discard_value_names);
832  Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
833  Opts.NoEscapingBlockTailCalls =
834  Args.hasArg(OPT_fno_escaping_block_tail_calls);
835  Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi);
836  Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable) ||
837  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
838  Args.hasArg(OPT_cl_fast_relaxed_math);
839  Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision);
840  Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
841  Args.hasArg(OPT_cl_finite_math_only) ||
842  Args.hasArg(OPT_cl_fast_relaxed_math));
843  Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
844  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
845  Args.hasArg(OPT_cl_finite_math_only) ||
846  Args.hasArg(OPT_cl_fast_relaxed_math));
847  Opts.NoSignedZeros = (Args.hasArg(OPT_fno_signed_zeros) ||
848  Args.hasArg(OPT_cl_no_signed_zeros) ||
849  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
850  Args.hasArg(OPT_cl_fast_relaxed_math));
851  Opts.Reassociate = Args.hasArg(OPT_mreassociate);
852  Opts.FlushDenorm = Args.hasArg(OPT_cl_denorms_are_zero) ||
853  (Args.hasArg(OPT_fcuda_is_device) &&
854  Args.hasArg(OPT_fcuda_flush_denormals_to_zero));
855  Opts.CorrectlyRoundedDivSqrt =
856  Args.hasArg(OPT_cl_fp32_correctly_rounded_divide_sqrt);
857  Opts.UniformWGSize =
858  Args.hasArg(OPT_cl_uniform_work_group_size);
859  Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
860  Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math);
861  Opts.NoTrappingMath = Args.hasArg(OPT_fno_trapping_math);
862  Opts.StrictFloatCastOverflow =
863  !Args.hasArg(OPT_fno_strict_float_cast_overflow);
864 
865  Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
866  Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
867  Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
868  Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
869  Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
870  Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
871  Opts.IncrementalLinkerCompatible =
872  Args.hasArg(OPT_mincremental_linker_compatible);
873  Opts.PIECopyRelocations =
874  Args.hasArg(OPT_mpie_copy_relocations);
875  Opts.NoPLT = Args.hasArg(OPT_fno_plt);
876  Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
877  Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
878  Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
879  Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
880  Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
881  Opts.StrictReturn = !Args.hasArg(OPT_fno_strict_return);
882  Opts.StrictVTablePointers = Args.hasArg(OPT_fstrict_vtable_pointers);
883  Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
884  Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
885  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
886  Args.hasArg(OPT_cl_fast_relaxed_math);
887  Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
888  Opts.RelocationModel = getRelocModel(Args, Diags);
889  Opts.ThreadModel = Args.getLastArgValue(OPT_mthread_model, "posix");
890  if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single")
891  Diags.Report(diag::err_drv_invalid_value)
892  << Args.getLastArg(OPT_mthread_model)->getAsString(Args)
893  << Opts.ThreadModel;
894  Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ);
895  Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array);
896 
897  Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections,
898  OPT_fno_function_sections, false);
899  Opts.DataSections = Args.hasFlag(OPT_fdata_sections,
900  OPT_fno_data_sections, false);
901  Opts.StackSizeSection =
902  Args.hasFlag(OPT_fstack_size_section, OPT_fno_stack_size_section, false);
903  Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names,
904  OPT_fno_unique_section_names, true);
905 
906  Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
907 
908  Opts.NoUseJumpTables = Args.hasArg(OPT_fno_jump_tables);
909 
910  Opts.NullPointerIsValid = Args.hasArg(OPT_fno_delete_null_pointer_checks);
911 
912  Opts.ProfileSampleAccurate = Args.hasArg(OPT_fprofile_sample_accurate);
913 
914  Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
915  Opts.PrepareForThinLTO = false;
916  if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
917  StringRef S = A->getValue();
918  if (S == "thin")
919  Opts.PrepareForThinLTO = true;
920  else if (S != "full")
921  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
922  }
923  Opts.LTOUnit = Args.hasFlag(OPT_flto_unit, OPT_fno_lto_unit, false);
924  Opts.EnableSplitLTOUnit = Args.hasArg(OPT_fsplit_lto_unit);
925  if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
926  if (IK.getLanguage() != InputKind::LLVM_IR)
927  Diags.Report(diag::err_drv_argument_only_allowed_with)
928  << A->getAsString(Args) << "-x ir";
929  Opts.ThinLTOIndexFile = Args.getLastArgValue(OPT_fthinlto_index_EQ);
930  }
931  if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
932  Opts.SaveTempsFilePrefix =
933  llvm::StringSwitch<std::string>(A->getValue())
934  .Case("obj", FrontendOpts.OutputFile)
935  .Default(llvm::sys::path::filename(FrontendOpts.OutputFile).str());
936 
937  Opts.ThinLinkBitcodeFile = Args.getLastArgValue(OPT_fthin_link_bitcode_EQ);
938 
939  Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
940 
941  Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
942  Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
943 
944  Opts.PreferVectorWidth = Args.getLastArgValue(OPT_mprefer_vector_width_EQ);
945 
946  Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
947  Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
948 
949  Opts.ControlFlowGuard = Args.hasArg(OPT_cfguard);
950 
951  Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
952  Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
953  Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
954  if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
955  Opts.CoverageDataFile = Args.getLastArgValue(OPT_coverage_data_file);
956  Opts.CoverageNotesFile = Args.getLastArgValue(OPT_coverage_notes_file);
957  Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum);
958  Opts.CoverageNoFunctionNamesInData =
959  Args.hasArg(OPT_coverage_no_function_names_in_data);
960  Opts.ProfileFilterFiles =
961  Args.getLastArgValue(OPT_fprofile_filter_files_EQ);
962  Opts.ProfileExcludeFiles =
963  Args.getLastArgValue(OPT_fprofile_exclude_files_EQ);
964  Opts.CoverageExitBlockBeforeBody =
965  Args.hasArg(OPT_coverage_exit_block_before_body);
966  if (Args.hasArg(OPT_coverage_version_EQ)) {
967  StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
968  if (CoverageVersion.size() != 4) {
969  Diags.Report(diag::err_drv_invalid_value)
970  << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
971  << CoverageVersion;
972  } else {
973  memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
974  }
975  }
976  }
977  // Handle -fembed-bitcode option.
978  if (Arg *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
979  StringRef Name = A->getValue();
980  unsigned Model = llvm::StringSwitch<unsigned>(Name)
981  .Case("off", CodeGenOptions::Embed_Off)
982  .Case("all", CodeGenOptions::Embed_All)
983  .Case("bitcode", CodeGenOptions::Embed_Bitcode)
984  .Case("marker", CodeGenOptions::Embed_Marker)
985  .Default(~0U);
986  if (Model == ~0U) {
987  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
988  Success = false;
989  } else
990  Opts.setEmbedBitcode(
991  static_cast<CodeGenOptions::EmbedBitcodeKind>(Model));
992  }
993  // FIXME: For backend options that are not yet recorded as function
994  // attributes in the IR, keep track of them so we can embed them in a
995  // separate data section and use them when building the bitcode.
996  if (Opts.getEmbedBitcode() == CodeGenOptions::Embed_All) {
997  for (const auto &A : Args) {
998  // Do not encode output and input.
999  if (A->getOption().getID() == options::OPT_o ||
1000  A->getOption().getID() == options::OPT_INPUT ||
1001  A->getOption().getID() == options::OPT_x ||
1002  A->getOption().getID() == options::OPT_fembed_bitcode ||
1003  (A->getOption().getGroup().isValid() &&
1004  A->getOption().getGroup().getID() == options::OPT_W_Group))
1005  continue;
1006  ArgStringList ASL;
1007  A->render(Args, ASL);
1008  for (const auto &arg : ASL) {
1009  StringRef ArgStr(arg);
1010  Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1011  // using \00 to separate each commandline options.
1012  Opts.CmdArgs.push_back('\0');
1013  }
1014  }
1015  }
1016 
1017  Opts.PreserveVec3Type = Args.hasArg(OPT_fpreserve_vec3_type);
1018  Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
1019  Opts.InstrumentFunctionsAfterInlining =
1020  Args.hasArg(OPT_finstrument_functions_after_inlining);
1021  Opts.InstrumentFunctionEntryBare =
1022  Args.hasArg(OPT_finstrument_function_entry_bare);
1023 
1024  Opts.XRayInstrumentFunctions =
1025  Args.hasArg(OPT_fxray_instrument);
1026  Opts.XRayAlwaysEmitCustomEvents =
1027  Args.hasArg(OPT_fxray_always_emit_customevents);
1028  Opts.XRayAlwaysEmitTypedEvents =
1029  Args.hasArg(OPT_fxray_always_emit_typedevents);
1030  Opts.XRayInstructionThreshold =
1031  getLastArgIntValue(Args, OPT_fxray_instruction_threshold_EQ, 200, Diags);
1032 
1033  auto XRayInstrBundles =
1034  Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1035  if (XRayInstrBundles.empty())
1037  else
1038  for (const auto &A : XRayInstrBundles)
1039  parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1040  Diags, Opts.XRayInstrumentationBundle);
1041 
1042  Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
1043  Opts.CallFEntry = Args.hasArg(OPT_mfentry);
1044  Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
1045 
1046  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1047  StringRef Name = A->getValue();
1048  if (Name == "full") {
1049  Opts.CFProtectionReturn = 1;
1050  Opts.CFProtectionBranch = 1;
1051  } else if (Name == "return")
1052  Opts.CFProtectionReturn = 1;
1053  else if (Name == "branch")
1054  Opts.CFProtectionBranch = 1;
1055  else if (Name != "none") {
1056  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1057  Success = false;
1058  }
1059  }
1060 
1061  if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
1062  OPT_compress_debug_sections_EQ)) {
1063  if (A->getOption().getID() == OPT_compress_debug_sections) {
1064  // TODO: be more clever about the compression type auto-detection
1065  Opts.setCompressDebugSections(llvm::DebugCompressionType::GNU);
1066  } else {
1067  auto DCT = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
1068  .Case("none", llvm::DebugCompressionType::None)
1069  .Case("zlib", llvm::DebugCompressionType::Z)
1070  .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
1072  Opts.setCompressDebugSections(DCT);
1073  }
1074  }
1075 
1076  Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
1077  Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
1078  for (auto *A :
1079  Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1081  F.Filename = A->getValue();
1082  if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1083  F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
1084  // When linking CUDA bitcode, propagate function attributes so that
1085  // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1086  F.PropagateAttrs = true;
1087  F.Internalize = true;
1088  }
1089  Opts.LinkBitcodeFiles.push_back(F);
1090  }
1091  Opts.SanitizeCoverageType =
1092  getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags);
1093  Opts.SanitizeCoverageIndirectCalls =
1094  Args.hasArg(OPT_fsanitize_coverage_indirect_calls);
1095  Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb);
1096  Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp);
1097  Opts.SanitizeCoverageTraceDiv = Args.hasArg(OPT_fsanitize_coverage_trace_div);
1098  Opts.SanitizeCoverageTraceGep = Args.hasArg(OPT_fsanitize_coverage_trace_gep);
1099  Opts.SanitizeCoverage8bitCounters =
1100  Args.hasArg(OPT_fsanitize_coverage_8bit_counters);
1101  Opts.SanitizeCoverageTracePC = Args.hasArg(OPT_fsanitize_coverage_trace_pc);
1102  Opts.SanitizeCoverageTracePCGuard =
1103  Args.hasArg(OPT_fsanitize_coverage_trace_pc_guard);
1104  Opts.SanitizeCoverageNoPrune = Args.hasArg(OPT_fsanitize_coverage_no_prune);
1105  Opts.SanitizeCoverageInline8bitCounters =
1106  Args.hasArg(OPT_fsanitize_coverage_inline_8bit_counters);
1107  Opts.SanitizeCoveragePCTable = Args.hasArg(OPT_fsanitize_coverage_pc_table);
1108  Opts.SanitizeCoverageStackDepth =
1109  Args.hasArg(OPT_fsanitize_coverage_stack_depth);
1110  Opts.SanitizeMemoryTrackOrigins =
1111  getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags);
1112  Opts.SanitizeMemoryUseAfterDtor =
1113  Args.hasFlag(OPT_fsanitize_memory_use_after_dtor,
1114  OPT_fno_sanitize_memory_use_after_dtor,
1115  false);
1116  Opts.SanitizeMinimalRuntime = Args.hasArg(OPT_fsanitize_minimal_runtime);
1117  Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso);
1118  Opts.SanitizeCfiICallGeneralizePointers =
1119  Args.hasArg(OPT_fsanitize_cfi_icall_generalize_pointers);
1120  Opts.SanitizeStats = Args.hasArg(OPT_fsanitize_stats);
1121  if (Arg *A = Args.getLastArg(
1122  OPT_fsanitize_address_poison_custom_array_cookie,
1123  OPT_fno_sanitize_address_poison_custom_array_cookie)) {
1124  Opts.SanitizeAddressPoisonCustomArrayCookie =
1125  A->getOption().getID() ==
1126  OPT_fsanitize_address_poison_custom_array_cookie;
1127  }
1128  if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_after_scope,
1129  OPT_fno_sanitize_address_use_after_scope)) {
1130  Opts.SanitizeAddressUseAfterScope =
1131  A->getOption().getID() == OPT_fsanitize_address_use_after_scope;
1132  }
1133  Opts.SanitizeAddressGlobalsDeadStripping =
1134  Args.hasArg(OPT_fsanitize_address_globals_dead_stripping);
1135  if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_odr_indicator,
1136  OPT_fno_sanitize_address_use_odr_indicator)) {
1137  Opts.SanitizeAddressUseOdrIndicator =
1138  A->getOption().getID() == OPT_fsanitize_address_use_odr_indicator;
1139  }
1140  Opts.SSPBufferSize =
1141  getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
1142  Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
1143  if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
1144  StringRef Val = A->getValue();
1145  unsigned StackAlignment = Opts.StackAlignment;
1146  Val.getAsInteger(10, StackAlignment);
1147  Opts.StackAlignment = StackAlignment;
1148  }
1149 
1150  if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) {
1151  StringRef Val = A->getValue();
1152  unsigned StackProbeSize = Opts.StackProbeSize;
1153  Val.getAsInteger(0, StackProbeSize);
1154  Opts.StackProbeSize = StackProbeSize;
1155  }
1156 
1157  Opts.NoStackArgProbe = Args.hasArg(OPT_mno_stack_arg_probe);
1158 
1159  if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
1160  StringRef Name = A->getValue();
1161  unsigned Method = llvm::StringSwitch<unsigned>(Name)
1162  .Case("legacy", CodeGenOptions::Legacy)
1163  .Case("non-legacy", CodeGenOptions::NonLegacy)
1164  .Case("mixed", CodeGenOptions::Mixed)
1165  .Default(~0U);
1166  if (Method == ~0U) {
1167  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1168  Success = false;
1169  } else {
1170  Opts.setObjCDispatchMethod(
1171  static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
1172  }
1173  }
1174 
1175 
1176  if (Args.hasArg(OPT_fno_objc_convert_messages_to_runtime_calls))
1177  Opts.ObjCConvertMessagesToRuntimeCalls = 0;
1178 
1179  if (Args.getLastArg(OPT_femulated_tls) ||
1180  Args.getLastArg(OPT_fno_emulated_tls)) {
1181  Opts.ExplicitEmulatedTLS = true;
1182  Opts.EmulatedTLS =
1183  Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false);
1184  }
1185 
1186  if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
1187  StringRef Name = A->getValue();
1188  unsigned Model = llvm::StringSwitch<unsigned>(Name)
1189  .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
1190  .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
1191  .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
1192  .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
1193  .Default(~0U);
1194  if (Model == ~0U) {
1195  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1196  Success = false;
1197  } else {
1198  Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
1199  }
1200  }
1201 
1202  if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1203  StringRef Val = A->getValue();
1204  if (Val == "ieee")
1205  Opts.FPDenormalMode = "ieee";
1206  else if (Val == "preserve-sign")
1207  Opts.FPDenormalMode = "preserve-sign";
1208  else if (Val == "positive-zero")
1209  Opts.FPDenormalMode = "positive-zero";
1210  else
1211  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1212  }
1213 
1214  if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) {
1215  if (A->getOption().matches(OPT_fpcc_struct_return)) {
1216  Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1217  } else {
1218  assert(A->getOption().matches(OPT_freg_struct_return));
1219  Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1220  }
1221  }
1222 
1223  Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
1224  Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option);
1225  bool NeedLocTracking = false;
1226 
1227  Opts.OptRecordFile = Args.getLastArgValue(OPT_opt_record_file);
1228  if (!Opts.OptRecordFile.empty())
1229  NeedLocTracking = true;
1230 
1231  if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
1232  Opts.OptRecordPasses = A->getValue();
1233  NeedLocTracking = true;
1234  }
1235 
1236  if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
1238  GenerateOptimizationRemarkRegex(Diags, Args, A);
1239  NeedLocTracking = true;
1240  }
1241 
1242  if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
1244  GenerateOptimizationRemarkRegex(Diags, Args, A);
1245  NeedLocTracking = true;
1246  }
1247 
1248  if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
1250  GenerateOptimizationRemarkRegex(Diags, Args, A);
1251  NeedLocTracking = true;
1252  }
1253 
1254  Opts.DiagnosticsWithHotness =
1255  Args.hasArg(options::OPT_fdiagnostics_show_hotness);
1256  bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
1257  bool UsingProfile = UsingSampleProfile ||
1258  (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
1259 
1260  if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1261  // An IR file will contain PGO as metadata
1263  Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1264  << "-fdiagnostics-show-hotness";
1265 
1266  Opts.DiagnosticsHotnessThreshold = getLastArgUInt64Value(
1267  Args, options::OPT_fdiagnostics_hotness_threshold_EQ, 0);
1268  if (Opts.DiagnosticsHotnessThreshold > 0 && !UsingProfile)
1269  Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1270  << "-fdiagnostics-hotness-threshold=";
1271 
1272  // If the user requested to use a sample profile for PGO, then the
1273  // backend will need to track source location information so the profile
1274  // can be incorporated into the IR.
1275  if (UsingSampleProfile)
1276  NeedLocTracking = true;
1277 
1278  // If the user requested a flag that requires source locations available in
1279  // the backend, make sure that the backend tracks source location information.
1280  if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
1281  Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
1282 
1283  Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
1284 
1285  // Parse -fsanitize-recover= arguments.
1286  // FIXME: Report unrecoverable sanitizers incorrectly specified here.
1287  parseSanitizerKinds("-fsanitize-recover=",
1288  Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
1289  Opts.SanitizeRecover);
1290  parseSanitizerKinds("-fsanitize-trap=",
1291  Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
1292  Opts.SanitizeTrap);
1293 
1294  Opts.CudaGpuBinaryFileName =
1295  Args.getLastArgValue(OPT_fcuda_include_gpubinary);
1296 
1297  Opts.Backchain = Args.hasArg(OPT_mbackchain);
1298 
1299  Opts.EmitCheckPathComponentsToStrip = getLastArgIntValue(
1300  Args, OPT_fsanitize_undefined_strip_path_components_EQ, 0, Diags);
1301 
1302  Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
1303 
1304  Opts.Addrsig = Args.hasArg(OPT_faddrsig);
1305 
1306  if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
1307  StringRef SignScope = A->getValue();
1308 
1309  if (SignScope.equals_lower("none"))
1310  Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::None);
1311  else if (SignScope.equals_lower("all"))
1312  Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::All);
1313  else if (SignScope.equals_lower("non-leaf"))
1314  Opts.setSignReturnAddress(
1315  CodeGenOptions::SignReturnAddressScope::NonLeaf);
1316  else
1317  Diags.Report(diag::err_drv_invalid_value)
1318  << A->getAsString(Args) << SignScope;
1319 
1320  if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
1321  StringRef SignKey = A->getValue();
1322  if (!SignScope.empty() && !SignKey.empty()) {
1323  if (SignKey.equals_lower("a_key"))
1324  Opts.setSignReturnAddressKey(
1325  CodeGenOptions::SignReturnAddressKeyValue::AKey);
1326  else if (SignKey.equals_lower("b_key"))
1327  Opts.setSignReturnAddressKey(
1328  CodeGenOptions::SignReturnAddressKeyValue::BKey);
1329  else
1330  Diags.Report(diag::err_drv_invalid_value)
1331  << A->getAsString(Args) << SignKey;
1332  }
1333  }
1334  }
1335 
1336  Opts.BranchTargetEnforcement = Args.hasArg(OPT_mbranch_target_enforce);
1337 
1338  Opts.KeepStaticConsts = Args.hasArg(OPT_fkeep_static_consts);
1339 
1340  Opts.SpeculativeLoadHardening = Args.hasArg(OPT_mspeculative_load_hardening);
1341 
1342  Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
1343 
1344  Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
1345 
1346  return Success;
1347 }
1348 
1350  ArgList &Args) {
1351  Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
1352  Opts.Targets = Args.getAllArgValues(OPT_MT);
1353  Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
1354  Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
1355  Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
1356  Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
1357  Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file);
1358  Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
1359  if (Args.hasArg(OPT_show_includes)) {
1360  // Writing both /showIncludes and preprocessor output to stdout
1361  // would produce interleaved output, so use stderr for /showIncludes.
1362  // This behaves the same as cl.exe, when /E, /EP or /P are passed.
1363  if (Args.hasArg(options::OPT_E) || Args.hasArg(options::OPT_P))
1365  else
1367  } else {
1369  }
1370  Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot);
1372  Args.getLastArgValue(OPT_module_dependency_dir);
1373  if (Args.hasArg(OPT_MV))
1375  // Add sanitizer blacklists as extra dependencies.
1376  // They won't be discovered by the regular preprocessor, so
1377  // we let make / ninja to know about this implicit dependency.
1378  Opts.ExtraDeps = Args.getAllArgValues(OPT_fdepfile_entry);
1379  // Only the -fmodule-file=<file> form.
1380  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1381  StringRef Val = A->getValue();
1382  if (Val.find('=') == StringRef::npos)
1383  Opts.ExtraDeps.push_back(Val);
1384  }
1385 }
1386 
1387 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
1388  // Color diagnostics default to auto ("on" if terminal supports) in the driver
1389  // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
1390  // Support both clang's -f[no-]color-diagnostics and gcc's
1391  // -f[no-]diagnostics-colors[=never|always|auto].
1392  enum {
1393  Colors_On,
1394  Colors_Off,
1395  Colors_Auto
1396  } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
1397  for (auto *A : Args) {
1398  const Option &O = A->getOption();
1399  if (O.matches(options::OPT_fcolor_diagnostics) ||
1400  O.matches(options::OPT_fdiagnostics_color)) {
1401  ShowColors = Colors_On;
1402  } else if (O.matches(options::OPT_fno_color_diagnostics) ||
1403  O.matches(options::OPT_fno_diagnostics_color)) {
1404  ShowColors = Colors_Off;
1405  } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
1406  StringRef Value(A->getValue());
1407  if (Value == "always")
1408  ShowColors = Colors_On;
1409  else if (Value == "never")
1410  ShowColors = Colors_Off;
1411  else if (Value == "auto")
1412  ShowColors = Colors_Auto;
1413  }
1414  }
1415  return ShowColors == Colors_On ||
1416  (ShowColors == Colors_Auto &&
1417  llvm::sys::Process::StandardErrHasColors());
1418 }
1419 
1420 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
1421  DiagnosticsEngine *Diags) {
1422  bool Success = true;
1423  for (const auto &Prefix : VerifyPrefixes) {
1424  // Every prefix must start with a letter and contain only alphanumeric
1425  // characters, hyphens, and underscores.
1426  auto BadChar = llvm::find_if(Prefix, [](char C) {
1427  return !isAlphanumeric(C) && C != '-' && C != '_';
1428  });
1429  if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
1430  Success = false;
1431  if (Diags) {
1432  Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
1433  Diags->Report(diag::note_drv_verify_prefix_spelling);
1434  }
1435  }
1436  }
1437  return Success;
1438 }
1439 
1440 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
1441  DiagnosticsEngine *Diags,
1442  bool DefaultDiagColor, bool DefaultShowOpt) {
1443  bool Success = true;
1444 
1445  Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
1446  if (Arg *A =
1447  Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
1448  Opts.DiagnosticSerializationFile = A->getValue();
1449  Opts.IgnoreWarnings = Args.hasArg(OPT_w);
1450  Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
1451  Opts.Pedantic = Args.hasArg(OPT_pedantic);
1452  Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
1453  Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
1454  Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
1455  Opts.ShowColumn = Args.hasFlag(OPT_fshow_column,
1456  OPT_fno_show_column,
1457  /*Default=*/true);
1458  Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
1459  Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
1460  Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths);
1461  Opts.ShowOptionNames =
1462  Args.hasFlag(OPT_fdiagnostics_show_option,
1463  OPT_fno_diagnostics_show_option, DefaultShowOpt);
1464 
1465  llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes));
1466 
1467  // Default behavior is to not to show note include stacks.
1468  Opts.ShowNoteIncludeStack = false;
1469  if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
1470  OPT_fno_diagnostics_show_note_include_stack))
1471  if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
1472  Opts.ShowNoteIncludeStack = true;
1473 
1474  StringRef ShowOverloads =
1475  Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
1476  if (ShowOverloads == "best")
1477  Opts.setShowOverloads(Ovl_Best);
1478  else if (ShowOverloads == "all")
1479  Opts.setShowOverloads(Ovl_All);
1480  else {
1481  Success = false;
1482  if (Diags)
1483  Diags->Report(diag::err_drv_invalid_value)
1484  << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
1485  << ShowOverloads;
1486  }
1487 
1488  StringRef ShowCategory =
1489  Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
1490  if (ShowCategory == "none")
1491  Opts.ShowCategories = 0;
1492  else if (ShowCategory == "id")
1493  Opts.ShowCategories = 1;
1494  else if (ShowCategory == "name")
1495  Opts.ShowCategories = 2;
1496  else {
1497  Success = false;
1498  if (Diags)
1499  Diags->Report(diag::err_drv_invalid_value)
1500  << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
1501  << ShowCategory;
1502  }
1503 
1504  StringRef Format =
1505  Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
1506  if (Format == "clang")
1507  Opts.setFormat(DiagnosticOptions::Clang);
1508  else if (Format == "msvc")
1509  Opts.setFormat(DiagnosticOptions::MSVC);
1510  else if (Format == "msvc-fallback") {
1511  Opts.setFormat(DiagnosticOptions::MSVC);
1512  Opts.CLFallbackMode = true;
1513  } else if (Format == "vi")
1514  Opts.setFormat(DiagnosticOptions::Vi);
1515  else {
1516  Success = false;
1517  if (Diags)
1518  Diags->Report(diag::err_drv_invalid_value)
1519  << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
1520  << Format;
1521  }
1522 
1523  Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
1524  Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
1525  Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
1526  Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
1527  Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
1528  if (Args.hasArg(OPT_verify))
1529  Opts.VerifyPrefixes.push_back("expected");
1530  // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
1531  // then sort it to prepare for fast lookup using std::binary_search.
1532  if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) {
1533  Opts.VerifyDiagnostics = false;
1534  Success = false;
1535  }
1536  else
1537  llvm::sort(Opts.VerifyPrefixes);
1539  Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
1540  Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
1541  Diags, DiagMask);
1542  if (Args.hasArg(OPT_verify_ignore_unexpected))
1543  DiagMask = DiagnosticLevelMask::All;
1544  Opts.setVerifyIgnoreUnexpected(DiagMask);
1545  Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
1546  Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
1547  Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
1548  Opts.MacroBacktraceLimit =
1549  getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
1551  Opts.TemplateBacktraceLimit = getLastArgIntValue(
1552  Args, OPT_ftemplate_backtrace_limit,
1554  Opts.ConstexprBacktraceLimit = getLastArgIntValue(
1555  Args, OPT_fconstexpr_backtrace_limit,
1557  Opts.SpellCheckingLimit = getLastArgIntValue(
1558  Args, OPT_fspell_checking_limit,
1560  Opts.SnippetLineLimit = getLastArgIntValue(
1561  Args, OPT_fcaret_diagnostics_max_lines,
1563  Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
1565  if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
1566  Opts.TabStop = DiagnosticOptions::DefaultTabStop;
1567  if (Diags)
1568  Diags->Report(diag::warn_ignoring_ftabstop_value)
1569  << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
1570  }
1571  Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags);
1572  addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
1573  addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
1574 
1575  return Success;
1576 }
1577 
1578 static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
1579  Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory);
1580 }
1581 
1582 /// Parse the argument to the -ftest-module-file-extension
1583 /// command-line argument.
1584 ///
1585 /// \returns true on error, false on success.
1586 static bool parseTestModuleFileExtensionArg(StringRef Arg,
1587  std::string &BlockName,
1588  unsigned &MajorVersion,
1589  unsigned &MinorVersion,
1590  bool &Hashed,
1591  std::string &UserInfo) {
1593  Arg.split(Args, ':', 5);
1594  if (Args.size() < 5)
1595  return true;
1596 
1597  BlockName = Args[0];
1598  if (Args[1].getAsInteger(10, MajorVersion)) return true;
1599  if (Args[2].getAsInteger(10, MinorVersion)) return true;
1600  if (Args[3].getAsInteger(2, Hashed)) return true;
1601  if (Args.size() > 4)
1602  UserInfo = Args[4];
1603  return false;
1604 }
1605 
1606 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
1607  DiagnosticsEngine &Diags,
1608  bool &IsHeaderFile) {
1610  if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
1611  switch (A->getOption().getID()) {
1612  default:
1613  llvm_unreachable("Invalid option in group!");
1614  case OPT_ast_list:
1615  Opts.ProgramAction = frontend::ASTDeclList; break;
1616  case OPT_ast_dump_all_EQ:
1617  case OPT_ast_dump_EQ: {
1618  unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
1619  .CaseLower("default", ADOF_Default)
1620  .CaseLower("json", ADOF_JSON)
1622 
1624  Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
1625  else {
1626  Diags.Report(diag::err_drv_invalid_value)
1627  << A->getAsString(Args) << A->getValue();
1628  Opts.ASTDumpFormat = ADOF_Default;
1629  }
1630  LLVM_FALLTHROUGH;
1631  }
1632  case OPT_ast_dump:
1633  case OPT_ast_dump_all:
1634  case OPT_ast_dump_lookups:
1635  Opts.ProgramAction = frontend::ASTDump; break;
1636  case OPT_ast_print:
1637  Opts.ProgramAction = frontend::ASTPrint; break;
1638  case OPT_ast_view:
1639  Opts.ProgramAction = frontend::ASTView; break;
1640  case OPT_compiler_options_dump:
1642  case OPT_dump_raw_tokens:
1643  Opts.ProgramAction = frontend::DumpRawTokens; break;
1644  case OPT_dump_tokens:
1645  Opts.ProgramAction = frontend::DumpTokens; break;
1646  case OPT_S:
1647  Opts.ProgramAction = frontend::EmitAssembly; break;
1648  case OPT_emit_llvm_bc:
1649  Opts.ProgramAction = frontend::EmitBC; break;
1650  case OPT_emit_html:
1651  Opts.ProgramAction = frontend::EmitHTML; break;
1652  case OPT_emit_llvm:
1653  Opts.ProgramAction = frontend::EmitLLVM; break;
1654  case OPT_emit_llvm_only:
1655  Opts.ProgramAction = frontend::EmitLLVMOnly; break;
1656  case OPT_emit_codegen_only:
1658  case OPT_emit_obj:
1659  Opts.ProgramAction = frontend::EmitObj; break;
1660  case OPT_fixit_EQ:
1661  Opts.FixItSuffix = A->getValue();
1662  LLVM_FALLTHROUGH;
1663  case OPT_fixit:
1664  Opts.ProgramAction = frontend::FixIt; break;
1665  case OPT_emit_module:
1667  case OPT_emit_module_interface:
1669  case OPT_emit_header_module:
1671  case OPT_emit_pch:
1672  Opts.ProgramAction = frontend::GeneratePCH; break;
1673  case OPT_init_only:
1674  Opts.ProgramAction = frontend::InitOnly; break;
1675  case OPT_fsyntax_only:
1677  case OPT_module_file_info:
1679  case OPT_verify_pch:
1680  Opts.ProgramAction = frontend::VerifyPCH; break;
1681  case OPT_print_preamble:
1682  Opts.ProgramAction = frontend::PrintPreamble; break;
1683  case OPT_E:
1685  case OPT_templight_dump:
1686  Opts.ProgramAction = frontend::TemplightDump; break;
1687  case OPT_rewrite_macros:
1688  Opts.ProgramAction = frontend::RewriteMacros; break;
1689  case OPT_rewrite_objc:
1690  Opts.ProgramAction = frontend::RewriteObjC; break;
1691  case OPT_rewrite_test:
1692  Opts.ProgramAction = frontend::RewriteTest; break;
1693  case OPT_analyze:
1694  Opts.ProgramAction = frontend::RunAnalysis; break;
1695  case OPT_migrate:
1696  Opts.ProgramAction = frontend::MigrateSource; break;
1697  case OPT_Eonly:
1699  }
1700  }
1701 
1702  if (const Arg* A = Args.getLastArg(OPT_plugin)) {
1703  Opts.Plugins.emplace_back(A->getValue(0));
1705  Opts.ActionName = A->getValue();
1706  }
1707  Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
1708  for (const auto *AA : Args.filtered(OPT_plugin_arg))
1709  Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
1710 
1711  for (const std::string &Arg :
1712  Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
1713  std::string BlockName;
1714  unsigned MajorVersion;
1715  unsigned MinorVersion;
1716  bool Hashed;
1717  std::string UserInfo;
1718  if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
1719  MinorVersion, Hashed, UserInfo)) {
1720  Diags.Report(diag::err_test_module_file_extension_format) << Arg;
1721 
1722  continue;
1723  }
1724 
1725  // Add the testing module file extension.
1726  Opts.ModuleFileExtensions.push_back(
1727  std::make_shared<TestModuleFileExtension>(
1728  BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
1729  }
1730 
1731  if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1732  Opts.CodeCompletionAt =
1733  ParsedSourceLocation::FromString(A->getValue());
1734  if (Opts.CodeCompletionAt.FileName.empty())
1735  Diags.Report(diag::err_drv_invalid_value)
1736  << A->getAsString(Args) << A->getValue();
1737  }
1738  Opts.DisableFree = Args.hasArg(OPT_disable_free);
1739 
1740  Opts.OutputFile = Args.getLastArgValue(OPT_o);
1741  Opts.Plugins = Args.getAllArgValues(OPT_load);
1742  Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
1743  Opts.ShowHelp = Args.hasArg(OPT_help);
1744  Opts.ShowStats = Args.hasArg(OPT_print_stats);
1745  Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
1746  Opts.TimeTrace = Args.hasArg(OPT_ftime_trace);
1747  Opts.ShowVersion = Args.hasArg(OPT_version);
1748  Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
1749  Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
1750  Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
1751  Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
1752  Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
1753  Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
1754  Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
1755  Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
1756  Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter);
1757  Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
1758  Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
1760  Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
1761  // Only the -fmodule-file=<file> form.
1762  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1763  StringRef Val = A->getValue();
1764  if (Val.find('=') == StringRef::npos)
1765  Opts.ModuleFiles.push_back(Val);
1766  }
1767  Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
1768  Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files);
1769  Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp);
1770 
1772  = Args.hasArg(OPT_code_completion_macros);
1774  = Args.hasArg(OPT_code_completion_patterns);
1776  = !Args.hasArg(OPT_no_code_completion_globals);
1778  = !Args.hasArg(OPT_no_code_completion_ns_level_decls);
1780  = Args.hasArg(OPT_code_completion_brief_comments);
1782  = Args.hasArg(OPT_code_completion_with_fixits);
1783 
1785  = Args.getLastArgValue(OPT_foverride_record_layout_EQ);
1786  Opts.AuxTriple = Args.getLastArgValue(OPT_aux_triple);
1787  Opts.StatsFile = Args.getLastArgValue(OPT_stats_file);
1788 
1789  if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
1790  OPT_arcmt_modify,
1791  OPT_arcmt_migrate)) {
1792  switch (A->getOption().getID()) {
1793  default:
1794  llvm_unreachable("missed a case");
1795  case OPT_arcmt_check:
1797  break;
1798  case OPT_arcmt_modify:
1800  break;
1801  case OPT_arcmt_migrate:
1803  break;
1804  }
1805  }
1806  Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
1808  = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
1810  = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
1811 
1812  if (Args.hasArg(OPT_objcmt_migrate_literals))
1814  if (Args.hasArg(OPT_objcmt_migrate_subscripting))
1816  if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
1818  if (Args.hasArg(OPT_objcmt_migrate_property))
1820  if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
1822  if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
1824  if (Args.hasArg(OPT_objcmt_migrate_annotation))
1826  if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
1828  if (Args.hasArg(OPT_objcmt_migrate_instancetype))
1830  if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
1832  if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
1834  if (Args.hasArg(OPT_objcmt_atomic_property))
1836  if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
1838  if (Args.hasArg(OPT_objcmt_migrate_designated_init))
1840  if (Args.hasArg(OPT_objcmt_migrate_all))
1842 
1843  Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path);
1844 
1847  Diags.Report(diag::err_drv_argument_not_allowed_with)
1848  << "ARC migration" << "ObjC migration";
1849  }
1850 
1852  if (const Arg *A = Args.getLastArg(OPT_x)) {
1853  StringRef XValue = A->getValue();
1854 
1855  // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
1856  // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
1857  bool Preprocessed = XValue.consume_back("-cpp-output");
1858  bool ModuleMap = XValue.consume_back("-module-map");
1859  IsHeaderFile =
1860  !Preprocessed && !ModuleMap && XValue.consume_back("-header");
1861 
1862  // Principal languages.
1863  DashX = llvm::StringSwitch<InputKind>(XValue)
1864  .Case("c", InputKind::C)
1865  .Case("cl", InputKind::OpenCL)
1866  .Case("cuda", InputKind::CUDA)
1867  .Case("hip", InputKind::HIP)
1868  .Case("c++", InputKind::CXX)
1869  .Case("objective-c", InputKind::ObjC)
1870  .Case("objective-c++", InputKind::ObjCXX)
1871  .Case("renderscript", InputKind::RenderScript)
1872  .Default(InputKind::Unknown);
1873 
1874  // "objc[++]-cpp-output" is an acceptable synonym for
1875  // "objective-c[++]-cpp-output".
1876  if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
1877  DashX = llvm::StringSwitch<InputKind>(XValue)
1878  .Case("objc", InputKind::ObjC)
1879  .Case("objc++", InputKind::ObjCXX)
1880  .Default(InputKind::Unknown);
1881 
1882  // Some special cases cannot be combined with suffixes.
1883  if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
1884  DashX = llvm::StringSwitch<InputKind>(XValue)
1885  .Case("cpp-output", InputKind(InputKind::C).getPreprocessed())
1886  .Case("assembler-with-cpp", InputKind::Asm)
1887  .Cases("ast", "pcm",
1889  .Case("ir", InputKind::LLVM_IR)
1890  .Default(InputKind::Unknown);
1891 
1892  if (DashX.isUnknown())
1893  Diags.Report(diag::err_drv_invalid_value)
1894  << A->getAsString(Args) << A->getValue();
1895 
1896  if (Preprocessed)
1897  DashX = DashX.getPreprocessed();
1898  if (ModuleMap)
1899  DashX = DashX.withFormat(InputKind::ModuleMap);
1900  }
1901 
1902  // '-' is the default input if none is given.
1903  std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
1904  Opts.Inputs.clear();
1905  if (Inputs.empty())
1906  Inputs.push_back("-");
1907  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1908  InputKind IK = DashX;
1909  if (IK.isUnknown()) {
1911  StringRef(Inputs[i]).rsplit('.').second);
1912  // FIXME: Warn on this?
1913  if (IK.isUnknown())
1914  IK = InputKind::C;
1915  // FIXME: Remove this hack.
1916  if (i == 0)
1917  DashX = IK;
1918  }
1919 
1920  // The -emit-module action implicitly takes a module map.
1922  IK.getFormat() == InputKind::Source)
1924 
1925  Opts.Inputs.emplace_back(std::move(Inputs[i]), IK);
1926  }
1927 
1928  return DashX;
1929 }
1930 
1931 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
1932  void *MainAddr) {
1933  std::string ClangExecutable =
1934  llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
1935  return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
1936 }
1937 
1938 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
1939  const std::string &WorkingDir) {
1940  Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
1941  Opts.Verbose = Args.hasArg(OPT_v);
1942  Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
1943  Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
1944  Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
1945  if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
1946  Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
1947  Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
1948 
1949  // Canonicalize -fmodules-cache-path before storing it.
1950  SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
1951  if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
1952  if (WorkingDir.empty())
1953  llvm::sys::fs::make_absolute(P);
1954  else
1955  llvm::sys::fs::make_absolute(WorkingDir, P);
1956  }
1957  llvm::sys::path::remove_dots(P);
1958  Opts.ModuleCachePath = P.str();
1959 
1960  Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path);
1961  // Only the -fmodule-file=<name>=<file> form.
1962  for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1963  StringRef Val = A->getValue();
1964  if (Val.find('=') != StringRef::npos)
1965  Opts.PrebuiltModuleFiles.insert(Val.split('='));
1966  }
1967  for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
1968  Opts.AddPrebuiltModulePath(A->getValue());
1969  Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
1970  Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content);
1972  !Args.hasArg(OPT_fmodules_disable_diagnostic_validation);
1973  Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps);
1974  Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
1976  getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
1977  Opts.ModuleCachePruneAfter =
1978  getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
1980  Args.hasArg(OPT_fmodules_validate_once_per_build_session);
1981  Opts.BuildSessionTimestamp =
1982  getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
1984  Args.hasArg(OPT_fmodules_validate_system_headers);
1985  if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
1986  Opts.ModuleFormat = A->getValue();
1987 
1988  for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
1989  StringRef MacroDef = A->getValue();
1990  Opts.ModulesIgnoreMacros.insert(
1991  llvm::CachedHashString(MacroDef.split('=').first));
1992  }
1993 
1994  // Add -I..., -F..., and -index-header-map options in order.
1995  bool IsIndexHeaderMap = false;
1996  bool IsSysrootSpecified =
1997  Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
1998  for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
1999  if (A->getOption().matches(OPT_index_header_map)) {
2000  // -index-header-map applies to the next -I or -F.
2001  IsIndexHeaderMap = true;
2002  continue;
2003  }
2004 
2006  IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
2007 
2008  bool IsFramework = A->getOption().matches(OPT_F);
2009  std::string Path = A->getValue();
2010 
2011  if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
2012  SmallString<32> Buffer;
2013  llvm::sys::path::append(Buffer, Opts.Sysroot,
2014  llvm::StringRef(A->getValue()).substr(1));
2015  Path = Buffer.str();
2016  }
2017 
2018  Opts.AddPath(Path, Group, IsFramework,
2019  /*IgnoreSysroot*/ true);
2020  IsIndexHeaderMap = false;
2021  }
2022 
2023  // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
2024  StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
2025  for (const auto *A :
2026  Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
2027  if (A->getOption().matches(OPT_iprefix))
2028  Prefix = A->getValue();
2029  else if (A->getOption().matches(OPT_iwithprefix))
2030  Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
2031  else
2032  Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
2033  }
2034 
2035  for (const auto *A : Args.filtered(OPT_idirafter))
2036  Opts.AddPath(A->getValue(), frontend::After, false, true);
2037  for (const auto *A : Args.filtered(OPT_iquote))
2038  Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
2039  for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
2040  Opts.AddPath(A->getValue(), frontend::System, false,
2041  !A->getOption().matches(OPT_iwithsysroot));
2042  for (const auto *A : Args.filtered(OPT_iframework))
2043  Opts.AddPath(A->getValue(), frontend::System, true, true);
2044  for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
2045  Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
2046  /*IgnoreSysRoot=*/false);
2047 
2048  // Add the paths for the various language specific isystem flags.
2049  for (const auto *A : Args.filtered(OPT_c_isystem))
2050  Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
2051  for (const auto *A : Args.filtered(OPT_cxx_isystem))
2052  Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
2053  for (const auto *A : Args.filtered(OPT_objc_isystem))
2054  Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
2055  for (const auto *A : Args.filtered(OPT_objcxx_isystem))
2056  Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
2057 
2058  // Add the internal paths from a driver that detects standard include paths.
2059  for (const auto *A :
2060  Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
2062  if (A->getOption().matches(OPT_internal_externc_isystem))
2063  Group = frontend::ExternCSystem;
2064  Opts.AddPath(A->getValue(), Group, false, true);
2065  }
2066 
2067  // Add the path prefixes which are implicitly treated as being system headers.
2068  for (const auto *A :
2069  Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
2070  Opts.AddSystemHeaderPrefix(
2071  A->getValue(), A->getOption().matches(OPT_system_header_prefix));
2072 
2073  for (const auto *A : Args.filtered(OPT_ivfsoverlay))
2074  Opts.AddVFSOverlayFile(A->getValue());
2075 }
2076 
2078  const llvm::Triple &T,
2079  PreprocessorOptions &PPOpts,
2080  LangStandard::Kind LangStd) {
2081  // Set some properties which depend solely on the input kind; it would be nice
2082  // to move these to the language standard, and have the driver resolve the
2083  // input kind + language standard.
2084  //
2085  // FIXME: Perhaps a better model would be for a single source file to have
2086  // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
2087  // simultaneously active?
2088  if (IK.getLanguage() == InputKind::Asm) {
2089  Opts.AsmPreprocessor = 1;
2090  } else if (IK.isObjectiveC()) {
2091  Opts.ObjC = 1;
2092  }
2093 
2094  if (LangStd == LangStandard::lang_unspecified) {
2095  // Based on the base language, pick one.
2096  switch (IK.getLanguage()) {
2097  case InputKind::Unknown:
2098  case InputKind::LLVM_IR:
2099  llvm_unreachable("Invalid input kind!");
2100  case InputKind::OpenCL:
2101  LangStd = LangStandard::lang_opencl10;
2102  break;
2103  case InputKind::CUDA:
2104  LangStd = LangStandard::lang_cuda;
2105  break;
2106  case InputKind::Asm:
2107  case InputKind::C:
2108 #if defined(CLANG_DEFAULT_STD_C)
2109  LangStd = CLANG_DEFAULT_STD_C;
2110 #else
2111  // The PS4 uses C99 as the default C standard.
2112  if (T.isPS4())
2113  LangStd = LangStandard::lang_gnu99;
2114  else
2115  LangStd = LangStandard::lang_gnu11;
2116 #endif
2117  break;
2118  case InputKind::ObjC:
2119 #if defined(CLANG_DEFAULT_STD_C)
2120  LangStd = CLANG_DEFAULT_STD_C;
2121 #else
2122  LangStd = LangStandard::lang_gnu11;
2123 #endif
2124  break;
2125  case InputKind::CXX:
2126  case InputKind::ObjCXX:
2127 #if defined(CLANG_DEFAULT_STD_CXX)
2128  LangStd = CLANG_DEFAULT_STD_CXX;
2129 #else
2130  LangStd = LangStandard::lang_gnucxx14;
2131 #endif
2132  break;
2134  LangStd = LangStandard::lang_c99;
2135  break;
2136  case InputKind::HIP:
2137  LangStd = LangStandard::lang_hip;
2138  break;
2139  }
2140  }
2141 
2143  Opts.LineComment = Std.hasLineComments();
2144  Opts.C99 = Std.isC99();
2145  Opts.C11 = Std.isC11();
2146  Opts.C17 = Std.isC17();
2147  Opts.C2x = Std.isC2x();
2148  Opts.CPlusPlus = Std.isCPlusPlus();
2149  Opts.CPlusPlus11 = Std.isCPlusPlus11();
2150  Opts.CPlusPlus14 = Std.isCPlusPlus14();
2151  Opts.CPlusPlus17 = Std.isCPlusPlus17();
2152  Opts.CPlusPlus2a = Std.isCPlusPlus2a();
2153  Opts.Digraphs = Std.hasDigraphs();
2154  Opts.GNUMode = Std.isGNUMode();
2155  Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus;
2156  Opts.HexFloats = Std.hasHexFloats();
2157  Opts.ImplicitInt = Std.hasImplicitInt();
2158 
2159  // Set OpenCL Version.
2160  Opts.OpenCL = Std.isOpenCL();
2161  if (LangStd == LangStandard::lang_opencl10)
2162  Opts.OpenCLVersion = 100;
2163  else if (LangStd == LangStandard::lang_opencl11)
2164  Opts.OpenCLVersion = 110;
2165  else if (LangStd == LangStandard::lang_opencl12)
2166  Opts.OpenCLVersion = 120;
2167  else if (LangStd == LangStandard::lang_opencl20)
2168  Opts.OpenCLVersion = 200;
2169  else if (LangStd == LangStandard::lang_openclcpp)
2170  Opts.OpenCLCPlusPlusVersion = 100;
2171 
2172  // OpenCL has some additional defaults.
2173  if (Opts.OpenCL) {
2174  Opts.AltiVec = 0;
2175  Opts.ZVector = 0;
2176  Opts.LaxVectorConversions = 0;
2177  Opts.setDefaultFPContractMode(LangOptions::FPC_On);
2178  Opts.NativeHalfType = 1;
2179  Opts.NativeHalfArgsAndReturns = 1;
2180  Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
2181  // Include default header file for OpenCL.
2182  if (Opts.IncludeDefaultHeader) {
2183  PPOpts.Includes.push_back("opencl-c.h");
2184  }
2185  }
2186 
2187  Opts.HIP = IK.getLanguage() == InputKind::HIP;
2188  Opts.CUDA = IK.getLanguage() == InputKind::CUDA || Opts.HIP;
2189  if (Opts.CUDA)
2190  // Set default FP_CONTRACT to FAST.
2191  Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
2192 
2193  Opts.RenderScript = IK.getLanguage() == InputKind::RenderScript;
2194  if (Opts.RenderScript) {
2195  Opts.NativeHalfType = 1;
2196  Opts.NativeHalfArgsAndReturns = 1;
2197  }
2198 
2199  // OpenCL and C++ both have bool, true, false keywords.
2200  Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
2201 
2202  // OpenCL has half keyword
2203  Opts.Half = Opts.OpenCL;
2204 
2205  // C++ has wchar_t keyword.
2206  Opts.WChar = Opts.CPlusPlus;
2207 
2208  Opts.GNUKeywords = Opts.GNUMode;
2209  Opts.CXXOperatorNames = Opts.CPlusPlus;
2210 
2211  Opts.AlignedAllocation = Opts.CPlusPlus17;
2212 
2213  Opts.DollarIdents = !Opts.AsmPreprocessor;
2214 
2215  // Enable [[]] attributes in C++11 and C2x by default.
2216  Opts.DoubleSquareBracketAttributes = Opts.CPlusPlus11 || Opts.C2x;
2217 }
2218 
2219 /// Attempt to parse a visibility value out of the given argument.
2220 static Visibility parseVisibility(Arg *arg, ArgList &args,
2221  DiagnosticsEngine &diags) {
2222  StringRef value = arg->getValue();
2223  if (value == "default") {
2224  return DefaultVisibility;
2225  } else if (value == "hidden" || value == "internal") {
2226  return HiddenVisibility;
2227  } else if (value == "protected") {
2228  // FIXME: diagnose if target does not support protected visibility
2229  return ProtectedVisibility;
2230  }
2231 
2232  diags.Report(diag::err_drv_invalid_value)
2233  << arg->getAsString(args) << value;
2234  return DefaultVisibility;
2235 }
2236 
2237 /// Check if input file kind and language standard are compatible.
2239  const LangStandard &S) {
2240  switch (IK.getLanguage()) {
2241  case InputKind::Unknown:
2242  case InputKind::LLVM_IR:
2243  llvm_unreachable("should not parse language flags for this input");
2244 
2245  case InputKind::C:
2246  case InputKind::ObjC:
2248  return S.getLanguage() == InputKind::C;
2249 
2250  case InputKind::OpenCL:
2251  return S.getLanguage() == InputKind::OpenCL;
2252 
2253  case InputKind::CXX:
2254  case InputKind::ObjCXX:
2255  return S.getLanguage() == InputKind::CXX;
2256 
2257  case InputKind::CUDA:
2258  // FIXME: What -std= values should be permitted for CUDA compilations?
2259  return S.getLanguage() == InputKind::CUDA ||
2260  S.getLanguage() == InputKind::CXX;
2261 
2262  case InputKind::HIP:
2263  return S.getLanguage() == InputKind::CXX ||
2264  S.getLanguage() == InputKind::HIP;
2265 
2266  case InputKind::Asm:
2267  // Accept (and ignore) all -std= values.
2268  // FIXME: The -std= value is not ignored; it affects the tokenization
2269  // and preprocessing rules if we're preprocessing this asm input.
2270  return true;
2271  }
2272 
2273  llvm_unreachable("unexpected input language");
2274 }
2275 
2276 /// Get language name for given input kind.
2277 static const StringRef GetInputKindName(InputKind IK) {
2278  switch (IK.getLanguage()) {
2279  case InputKind::C:
2280  return "C";
2281  case InputKind::ObjC:
2282  return "Objective-C";
2283  case InputKind::CXX:
2284  return "C++";
2285  case InputKind::ObjCXX:
2286  return "Objective-C++";
2287  case InputKind::OpenCL:
2288  return "OpenCL";
2289  case InputKind::CUDA:
2290  return "CUDA";
2292  return "RenderScript";
2293  case InputKind::HIP:
2294  return "HIP";
2295 
2296  case InputKind::Asm:
2297  return "Asm";
2298  case InputKind::LLVM_IR:
2299  return "LLVM IR";
2300 
2301  case InputKind::Unknown:
2302  break;
2303  }
2304  llvm_unreachable("unknown input language");
2305 }
2306 
2307 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
2308  const TargetOptions &TargetOpts,
2309  PreprocessorOptions &PPOpts,
2310  DiagnosticsEngine &Diags) {
2311  // FIXME: Cleanup per-file based stuff.
2313  if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
2314  LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
2315 #define LANGSTANDARD(id, name, lang, desc, features) \
2316  .Case(name, LangStandard::lang_##id)
2317 #define LANGSTANDARD_ALIAS(id, alias) \
2318  .Case(alias, LangStandard::lang_##id)
2319 #include "clang/Frontend/LangStandards.def"
2321  if (LangStd == LangStandard::lang_unspecified) {
2322  Diags.Report(diag::err_drv_invalid_value)
2323  << A->getAsString(Args) << A->getValue();
2324  // Report supported standards with short description.
2325  for (unsigned KindValue = 0;
2326  KindValue != LangStandard::lang_unspecified;
2327  ++KindValue) {
2329  static_cast<LangStandard::Kind>(KindValue));
2330  if (IsInputCompatibleWithStandard(IK, Std)) {
2331  auto Diag = Diags.Report(diag::note_drv_use_standard);
2332  Diag << Std.getName() << Std.getDescription();
2333  unsigned NumAliases = 0;
2334 #define LANGSTANDARD(id, name, lang, desc, features)
2335 #define LANGSTANDARD_ALIAS(id, alias) \
2336  if (KindValue == LangStandard::lang_##id) ++NumAliases;
2337 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
2338 #include "clang/Frontend/LangStandards.def"
2339  Diag << NumAliases;
2340 #define LANGSTANDARD(id, name, lang, desc, features)
2341 #define LANGSTANDARD_ALIAS(id, alias) \
2342  if (KindValue == LangStandard::lang_##id) Diag << alias;
2343 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
2344 #include "clang/Frontend/LangStandards.def"
2345  }
2346  }
2347  } else {
2348  // Valid standard, check to make sure language and standard are
2349  // compatible.
2351  if (!IsInputCompatibleWithStandard(IK, Std)) {
2352  Diags.Report(diag::err_drv_argument_not_allowed_with)
2353  << A->getAsString(Args) << GetInputKindName(IK);
2354  }
2355  }
2356  }
2357 
2358  if (Args.hasArg(OPT_fno_dllexport_inlines))
2359  Opts.DllExportInlines = false;
2360 
2361  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2362  StringRef Name = A->getValue();
2363  if (Name == "full" || Name == "branch") {
2364  Opts.CFProtectionBranch = 1;
2365  }
2366  }
2367  // -cl-std only applies for OpenCL language standards.
2368  // Override the -std option in this case.
2369  if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
2370  LangStandard::Kind OpenCLLangStd
2371  = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
2372  .Cases("cl", "CL", LangStandard::lang_opencl10)
2373  .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
2374  .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
2375  .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
2376  .Case("c++", LangStandard::lang_openclcpp)
2378 
2379  if (OpenCLLangStd == LangStandard::lang_unspecified) {
2380  Diags.Report(diag::err_drv_invalid_value)
2381  << A->getAsString(Args) << A->getValue();
2382  }
2383  else
2384  LangStd = OpenCLLangStd;
2385  }
2386 
2387  Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
2388 
2389  llvm::Triple T(TargetOpts.Triple);
2390  CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd);
2391 
2392  // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
2393  // This option should be deprecated for CL > 1.0 because
2394  // this option was added for compatibility with OpenCL 1.0.
2395  if (Args.getLastArg(OPT_cl_strict_aliasing)
2396  && Opts.OpenCLVersion > 100) {
2397  Diags.Report(diag::warn_option_invalid_ocl_version)
2398  << Opts.getOpenCLVersionTuple().getAsString()
2399  << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
2400  }
2401 
2402  // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
2403  // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
2404  // while a subset (the non-C++ GNU keywords) is provided by GCC's
2405  // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
2406  // name, as it doesn't seem a useful distinction.
2407  Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
2408  Opts.GNUKeywords);
2409 
2410  Opts.Digraphs = Args.hasFlag(OPT_fdigraphs, OPT_fno_digraphs, Opts.Digraphs);
2411 
2412  if (Args.hasArg(OPT_fno_operator_names))
2413  Opts.CXXOperatorNames = 0;
2414 
2415  if (Args.hasArg(OPT_fcuda_is_device))
2416  Opts.CUDAIsDevice = 1;
2417 
2418  if (Args.hasArg(OPT_fcuda_allow_variadic_functions))
2419  Opts.CUDAAllowVariadicFunctions = 1;
2420 
2421  if (Args.hasArg(OPT_fno_cuda_host_device_constexpr))
2422  Opts.CUDAHostDeviceConstexpr = 0;
2423 
2424  if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals))
2425  Opts.CUDADeviceApproxTranscendentals = 1;
2426 
2427  Opts.GPURelocatableDeviceCode = Args.hasArg(OPT_fgpu_rdc);
2428 
2429  if (Opts.ObjC) {
2430  if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
2431  StringRef value = arg->getValue();
2432  if (Opts.ObjCRuntime.tryParse(value))
2433  Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
2434  }
2435 
2436  if (Args.hasArg(OPT_fobjc_gc_only))
2437  Opts.setGC(LangOptions::GCOnly);
2438  else if (Args.hasArg(OPT_fobjc_gc))
2439  Opts.setGC(LangOptions::HybridGC);
2440  else if (Args.hasArg(OPT_fobjc_arc)) {
2441  Opts.ObjCAutoRefCount = 1;
2442  if (!Opts.ObjCRuntime.allowsARC())
2443  Diags.Report(diag::err_arc_unsupported_on_runtime);
2444  }
2445 
2446  // ObjCWeakRuntime tracks whether the runtime supports __weak, not
2447  // whether the feature is actually enabled. This is predominantly
2448  // determined by -fobjc-runtime, but we allow it to be overridden
2449  // from the command line for testing purposes.
2450  if (Args.hasArg(OPT_fobjc_runtime_has_weak))
2451  Opts.ObjCWeakRuntime = 1;
2452  else
2453  Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
2454 
2455  // ObjCWeak determines whether __weak is actually enabled.
2456  // Note that we allow -fno-objc-weak to disable this even in ARC mode.
2457  if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
2458  if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
2459  assert(!Opts.ObjCWeak);
2460  } else if (Opts.getGC() != LangOptions::NonGC) {
2461  Diags.Report(diag::err_objc_weak_with_gc);
2462  } else if (!Opts.ObjCWeakRuntime) {
2463  Diags.Report(diag::err_objc_weak_unsupported);
2464  } else {
2465  Opts.ObjCWeak = 1;
2466  }
2467  } else if (Opts.ObjCAutoRefCount) {
2468  Opts.ObjCWeak = Opts.ObjCWeakRuntime;
2469  }
2470 
2471  if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
2472  Opts.ObjCInferRelatedResultType = 0;
2473 
2474  if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
2475  Opts.ObjCSubscriptingLegacyRuntime =
2477  }
2478 
2479  if (Args.hasArg(OPT_fgnu89_inline)) {
2480  if (Opts.CPlusPlus)
2481  Diags.Report(diag::err_drv_argument_not_allowed_with)
2482  << "-fgnu89-inline" << GetInputKindName(IK);
2483  else
2484  Opts.GNUInline = 1;
2485  }
2486 
2487  if (Args.hasArg(OPT_fapple_kext)) {
2488  if (!Opts.CPlusPlus)
2489  Diags.Report(diag::warn_c_kext);
2490  else
2491  Opts.AppleKext = 1;
2492  }
2493 
2494  if (Args.hasArg(OPT_print_ivar_layout))
2495  Opts.ObjCGCBitmapPrint = 1;
2496 
2497  if (Args.hasArg(OPT_fno_constant_cfstrings))
2498  Opts.NoConstantCFStrings = 1;
2499  if (const auto *A = Args.getLastArg(OPT_fcf_runtime_abi_EQ))
2500  Opts.CFRuntime =
2501  llvm::StringSwitch<LangOptions::CoreFoundationABI>(A->getValue())
2502  .Cases("unspecified", "standalone", "objc",
2504  .Cases("swift", "swift-5.0",
2506  .Case("swift-4.2", LangOptions::CoreFoundationABI::Swift4_2)
2507  .Case("swift-4.1", LangOptions::CoreFoundationABI::Swift4_1)
2509 
2510  if (Args.hasArg(OPT_fzvector))
2511  Opts.ZVector = 1;
2512 
2513  if (Args.hasArg(OPT_pthread))
2514  Opts.POSIXThreads = 1;
2515 
2516  // The value-visibility mode defaults to "default".
2517  if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
2518  Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
2519  } else {
2520  Opts.setValueVisibilityMode(DefaultVisibility);
2521  }
2522 
2523  // The type-visibility mode defaults to the value-visibility mode.
2524  if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
2525  Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
2526  } else {
2527  Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
2528  }
2529 
2530  if (Args.hasArg(OPT_fvisibility_inlines_hidden))
2531  Opts.InlineVisibilityHidden = 1;
2532 
2533  if (Args.hasArg(OPT_fvisibility_global_new_delete_hidden))
2534  Opts.GlobalAllocationFunctionVisibilityHidden = 1;
2535 
2536  if (Args.hasArg(OPT_fapply_global_visibility_to_externs))
2537  Opts.SetVisibilityForExternDecls = 1;
2538 
2539  if (Args.hasArg(OPT_ftrapv)) {
2540  Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
2541  // Set the handler, if one is specified.
2542  Opts.OverflowHandler =
2543  Args.getLastArgValue(OPT_ftrapv_handler);
2544  }
2545  else if (Args.hasArg(OPT_fwrapv))
2546  Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
2547 
2548  Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
2549  Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
2550  Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
2551  Opts.MSCompatibilityVersion = 0;
2552  if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
2553  VersionTuple VT;
2554  if (VT.tryParse(A->getValue()))
2555  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2556  << A->getValue();
2557  Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
2558  VT.getMinor().getValueOr(0) * 100000 +
2559  VT.getSubminor().getValueOr(0);
2560  }
2561 
2562  // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
2563  // is specified, or -std is set to a conforming mode.
2564  // Trigraphs are disabled by default in c++1z onwards.
2565  Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17;
2566  Opts.Trigraphs =
2567  Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
2568 
2569  Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
2570  OPT_fno_dollars_in_identifiers,
2571  Opts.DollarIdents);
2572  Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
2573  Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags);
2574  Opts.Borland = Args.hasArg(OPT_fborland_extensions);
2575  Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
2576  Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
2577  Opts.ConstStrings);
2578  if (Args.hasArg(OPT_fno_lax_vector_conversions))
2579  Opts.LaxVectorConversions = 0;
2580  if (Args.hasArg(OPT_fno_threadsafe_statics))
2581  Opts.ThreadsafeStatics = 0;
2582  Opts.Exceptions = Args.hasArg(OPT_fexceptions);
2583  Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
2584  Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
2585 
2586  // -ffixed-point
2587  Opts.FixedPoint =
2588  Args.hasFlag(OPT_ffixed_point, OPT_fno_fixed_point, /*Default=*/false) &&
2589  !Opts.CPlusPlus;
2590  Opts.PaddingOnUnsignedFixedPoint =
2591  Args.hasFlag(OPT_fpadding_on_unsigned_fixed_point,
2592  OPT_fno_padding_on_unsigned_fixed_point,
2593  /*Default=*/false) &&
2594  Opts.FixedPoint;
2595 
2596  // Handle exception personalities
2597  Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
2598  options::OPT_fseh_exceptions,
2599  options::OPT_fdwarf_exceptions);
2600  if (A) {
2601  const Option &Opt = A->getOption();
2602  llvm::Triple T(TargetOpts.Triple);
2603  if (T.isWindowsMSVCEnvironment())
2604  Diags.Report(diag::err_fe_invalid_exception_model)
2605  << Opt.getName() << T.str();
2606 
2607  Opts.SjLjExceptions = Opt.matches(options::OPT_fsjlj_exceptions);
2608  Opts.SEHExceptions = Opt.matches(options::OPT_fseh_exceptions);
2609  Opts.DWARFExceptions = Opt.matches(options::OPT_fdwarf_exceptions);
2610  }
2611 
2612  Opts.ExternCNoUnwind = Args.hasArg(OPT_fexternc_nounwind);
2613  Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
2614 
2615  Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti);
2616  Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data);
2617  Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
2618  && Opts.OpenCLVersion == 200);
2619  Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
2620  Opts.Coroutines = Opts.CPlusPlus2a || Args.hasArg(OPT_fcoroutines_ts);
2621 
2622  Opts.DoubleSquareBracketAttributes =
2623  Args.hasFlag(OPT_fdouble_square_bracket_attributes,
2624  OPT_fno_double_square_bracket_attributes,
2625  Opts.DoubleSquareBracketAttributes);
2626 
2627  Opts.CPlusPlusModules = Opts.CPlusPlus2a;
2628  Opts.ModulesTS = Args.hasArg(OPT_fmodules_ts);
2629  Opts.Modules =
2630  Args.hasArg(OPT_fmodules) || Opts.ModulesTS || Opts.CPlusPlusModules;
2631  Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse);
2632  Opts.ModulesDeclUse =
2633  Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse;
2634  // FIXME: We only need this in C++ modules / Modules TS if we might textually
2635  // enter a different module (eg, when building a header unit).
2636  Opts.ModulesLocalVisibility =
2637  Args.hasArg(OPT_fmodules_local_submodule_visibility) || Opts.ModulesTS ||
2638  Opts.CPlusPlusModules;
2639  Opts.ModulesCodegen = Args.hasArg(OPT_fmodules_codegen);
2640  Opts.ModulesDebugInfo = Args.hasArg(OPT_fmodules_debuginfo);
2641  Opts.ModulesSearchAll = Opts.Modules &&
2642  !Args.hasArg(OPT_fno_modules_search_all) &&
2643  Args.hasArg(OPT_fmodules_search_all);
2644  Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
2645  Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules);
2646  Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
2647  Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
2648  Opts.Char8 = Args.hasFlag(OPT_fchar8__t, OPT_fno_char8__t, Opts.CPlusPlus2a);
2649  if (const Arg *A = Args.getLastArg(OPT_fwchar_type_EQ)) {
2650  Opts.WCharSize = llvm::StringSwitch<unsigned>(A->getValue())
2651  .Case("char", 1)
2652  .Case("short", 2)
2653  .Case("int", 4)
2654  .Default(0);
2655  if (Opts.WCharSize == 0)
2656  Diags.Report(diag::err_fe_invalid_wchar_type) << A->getValue();
2657  }
2658  Opts.WCharIsSigned = Args.hasFlag(OPT_fsigned_wchar, OPT_fno_signed_wchar, true);
2659  Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
2660  Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
2661  Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
2662  if (!Opts.NoBuiltin)
2664  Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
2665  Opts.RelaxedTemplateTemplateArgs =
2666  Args.hasArg(OPT_frelaxed_template_template_args);
2667  Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation);
2668  Opts.AlignedAllocation =
2669  Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation,
2670  Opts.AlignedAllocation);
2671  Opts.AlignedAllocationUnavailable =
2672  Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable);
2673  Opts.NewAlignOverride =
2674  getLastArgIntValue(Args, OPT_fnew_alignment_EQ, 0, Diags);
2675  if (Opts.NewAlignOverride && !llvm::isPowerOf2_32(Opts.NewAlignOverride)) {
2676  Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
2677  Diags.Report(diag::err_fe_invalid_alignment) << A->getAsString(Args)
2678  << A->getValue();
2679  Opts.NewAlignOverride = 0;
2680  }
2681  Opts.ConceptsTS = Args.hasArg(OPT_fconcepts_ts);
2682  Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
2683  Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
2684  Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
2685  Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
2686  Opts.InstantiationDepth =
2687  getLastArgIntValue(Args, OPT_ftemplate_depth, 1024, Diags);
2688  Opts.ArrowDepth =
2689  getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags);
2690  Opts.ConstexprCallDepth =
2691  getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
2692  Opts.ConstexprStepLimit =
2693  getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
2694  Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
2695  Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
2696  Opts.NumLargeByValueCopy =
2697  getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
2698  Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
2700  Args.getLastArgValue(OPT_fconstant_string_class);
2701  Opts.ObjCDefaultSynthProperties =
2702  !Args.hasArg(OPT_disable_objc_default_synthesize_properties);
2703  Opts.EncodeExtendedBlockSig =
2704  Args.hasArg(OPT_fencode_extended_block_signature);
2705  Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
2706  Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
2707  Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
2708  Opts.AlignDouble = Args.hasArg(OPT_malign_double);
2709  Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
2710  Opts.ROPI = Args.hasArg(OPT_fropi);
2711  Opts.RWPI = Args.hasArg(OPT_frwpi);
2712  Opts.PIE = Args.hasArg(OPT_pic_is_pie);
2713  Opts.Static = Args.hasArg(OPT_static_define);
2714  Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
2715  Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
2716  || Args.hasArg(OPT_fdump_record_layouts);
2717  Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
2718  Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
2719  Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
2720  Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
2721  Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
2722  Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
2723  Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
2724  Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
2725  Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
2726  Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
2727  Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
2728  Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
2729  Opts.ModuleName = Args.getLastArgValue(OPT_fmodule_name_EQ);
2730  Opts.CurrentModule = Opts.ModuleName;
2731  Opts.AppExt = Args.hasArg(OPT_fapplication_extension);
2732  Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
2733  llvm::sort(Opts.ModuleFeatures);
2734  Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type);
2735  Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns);
2736  // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns
2737  // is enabled.
2738  Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns)
2739  | Opts.NativeHalfArgsAndReturns;
2740  Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm);
2741  Opts.Cmse = Args.hasArg(OPT_mcmse); // Armv8-M Security Extensions
2742 
2743  // __declspec is enabled by default for the PS4 by the driver, and also
2744  // enabled for Microsoft Extensions or Borland Extensions, here.
2745  //
2746  // FIXME: __declspec is also currently enabled for CUDA, but isn't really a
2747  // CUDA extension. However, it is required for supporting
2748  // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has
2749  // been rewritten in terms of something more generic, remove the Opts.CUDA
2750  // term here.
2751  Opts.DeclSpecKeyword =
2752  Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec,
2753  (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA));
2754 
2755  if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) {
2756  switch (llvm::StringSwitch<unsigned>(A->getValue())
2757  .Case("target", LangOptions::ASMM_Target)
2758  .Case("no", LangOptions::ASMM_Off)
2759  .Case("yes", LangOptions::ASMM_On)
2760  .Default(255)) {
2761  default:
2762  Diags.Report(diag::err_drv_invalid_value)
2763  << "-faddress-space-map-mangling=" << A->getValue();
2764  break;
2766  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target);
2767  break;
2768  case LangOptions::ASMM_On:
2769  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On);
2770  break;
2771  case LangOptions::ASMM_Off:
2772  Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off);
2773  break;
2774  }
2775  }
2776 
2777  if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) {
2779  llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>(
2780  A->getValue())
2781  .Case("single",
2783  .Case("multiple",
2785  .Case("virtual",
2787  .Default(LangOptions::PPTMK_BestCase);
2788  if (InheritanceModel == LangOptions::PPTMK_BestCase)
2789  Diags.Report(diag::err_drv_invalid_value)
2790  << "-fms-memptr-rep=" << A->getValue();
2791 
2792  Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel);
2793  }
2794 
2795  // Check for MS default calling conventions being specified.
2796  if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
2798  llvm::StringSwitch<LangOptions::DefaultCallingConvention>(A->getValue())
2799  .Case("cdecl", LangOptions::DCC_CDecl)
2800  .Case("fastcall", LangOptions::DCC_FastCall)
2801  .Case("stdcall", LangOptions::DCC_StdCall)
2802  .Case("vectorcall", LangOptions::DCC_VectorCall)
2803  .Case("regcall", LangOptions::DCC_RegCall)
2804  .Default(LangOptions::DCC_None);
2805  if (DefaultCC == LangOptions::DCC_None)
2806  Diags.Report(diag::err_drv_invalid_value)
2807  << "-fdefault-calling-conv=" << A->getValue();
2808 
2809  llvm::Triple T(TargetOpts.Triple);
2810  llvm::Triple::ArchType Arch = T.getArch();
2811  bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
2812  DefaultCC == LangOptions::DCC_StdCall) &&
2813  Arch != llvm::Triple::x86;
2814  emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
2815  DefaultCC == LangOptions::DCC_RegCall) &&
2816  !(Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64);
2817  if (emitError)
2818  Diags.Report(diag::err_drv_argument_not_allowed_with)
2819  << A->getSpelling() << T.getTriple();
2820  else
2821  Opts.setDefaultCallingConv(DefaultCC);
2822  }
2823 
2824  // -mrtd option
2825  if (Arg *A = Args.getLastArg(OPT_mrtd)) {
2826  if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
2827  Diags.Report(diag::err_drv_argument_not_allowed_with)
2828  << A->getSpelling() << "-fdefault-calling-conv";
2829  else {
2830  llvm::Triple T(TargetOpts.Triple);
2831  if (T.getArch() != llvm::Triple::x86)
2832  Diags.Report(diag::err_drv_argument_not_allowed_with)
2833  << A->getSpelling() << T.getTriple();
2834  else
2835  Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
2836  }
2837  }
2838 
2839  // Check if -fopenmp is specified.
2840  Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 1 : 0;
2841  // Check if -fopenmp-simd is specified.
2842  bool IsSimdSpecified =
2843  Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
2844  /*Default=*/false);
2845  Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
2846  Opts.OpenMPUseTLS =
2847  Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
2848  Opts.OpenMPIsDevice =
2849  Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
2850  bool IsTargetSpecified =
2851  Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
2852 
2853  if (Opts.OpenMP || Opts.OpenMPSimd) {
2854  if (int Version = getLastArgIntValue(
2855  Args, OPT_fopenmp_version_EQ,
2856  (IsSimdSpecified || IsTargetSpecified) ? 45 : Opts.OpenMP, Diags))
2857  Opts.OpenMP = Version;
2858  else if (IsSimdSpecified || IsTargetSpecified)
2859  Opts.OpenMP = 45;
2860  // Provide diagnostic when a given target is not expected to be an OpenMP
2861  // device or host.
2862  if (!Opts.OpenMPIsDevice) {
2863  switch (T.getArch()) {
2864  default:
2865  break;
2866  // Add unsupported host targets here:
2867  case llvm::Triple::nvptx:
2868  case llvm::Triple::nvptx64:
2869  Diags.Report(diag::err_drv_omp_host_target_not_supported)
2870  << TargetOpts.Triple;
2871  break;
2872  }
2873  }
2874  }
2875 
2876  // Set the flag to prevent the implementation from emitting device exception
2877  // handling code for those requiring so.
2878  if ((Opts.OpenMPIsDevice && T.isNVPTX()) || Opts.OpenCLCPlusPlus) {
2879  Opts.Exceptions = 0;
2880  Opts.CXXExceptions = 0;
2881  }
2882  if (Opts.OpenMPIsDevice && T.isNVPTX()) {
2883  Opts.OpenMPCUDANumSMs =
2884  getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
2885  Opts.OpenMPCUDANumSMs, Diags);
2886  Opts.OpenMPCUDABlocksPerSM =
2887  getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
2888  Opts.OpenMPCUDABlocksPerSM, Diags);
2889  Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
2890  Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
2891  Opts.OpenMPCUDAReductionBufNum, Diags);
2892  }
2893 
2894  // Prevent auto-widening the representation of loop counters during an
2895  // OpenMP collapse clause.
2896  Opts.OpenMPOptimisticCollapse =
2897  Args.hasArg(options::OPT_fopenmp_optimistic_collapse) ? 1 : 0;
2898 
2899  // Get the OpenMP target triples if any.
2900  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
2901 
2902  for (unsigned i = 0; i < A->getNumValues(); ++i) {
2903  llvm::Triple TT(A->getValue(i));
2904 
2905  if (TT.getArch() == llvm::Triple::UnknownArch ||
2906  !(TT.getArch() == llvm::Triple::ppc ||
2907  TT.getArch() == llvm::Triple::ppc64 ||
2908  TT.getArch() == llvm::Triple::ppc64le ||
2909  TT.getArch() == llvm::Triple::nvptx ||
2910  TT.getArch() == llvm::Triple::nvptx64 ||
2911  TT.getArch() == llvm::Triple::x86 ||
2912  TT.getArch() == llvm::Triple::x86_64))
2913  Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
2914  else
2915  Opts.OMPTargetTriples.push_back(TT);
2916  }
2917  }
2918 
2919  // Get OpenMP host file path if any and report if a non existent file is
2920  // found
2921  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
2922  Opts.OMPHostIRFile = A->getValue();
2923  if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
2924  Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
2925  << Opts.OMPHostIRFile;
2926  }
2927 
2928  Opts.SYCLIsDevice = Args.hasArg(options::OPT_fsycl_is_device);
2929 
2930  // Set CUDA mode for OpenMP target NVPTX if specified in options
2931  Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && T.isNVPTX() &&
2932  Args.hasArg(options::OPT_fopenmp_cuda_mode);
2933 
2934  // Set CUDA mode for OpenMP target NVPTX if specified in options
2935  Opts.OpenMPCUDAForceFullRuntime =
2936  Opts.OpenMPIsDevice && T.isNVPTX() &&
2937  Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime);
2938 
2939  // Record whether the __DEPRECATED define was requested.
2940  Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
2941  OPT_fno_deprecated_macro,
2942  Opts.Deprecated);
2943 
2944  // FIXME: Eliminate this dependency.
2945  unsigned Opt = getOptimizationLevel(Args, IK, Diags),
2946  OptSize = getOptimizationLevelSize(Args);
2947  Opts.Optimize = Opt != 0;
2948  Opts.OptimizeSize = OptSize != 0;
2949 
2950  // This is the __NO_INLINE__ define, which just depends on things like the
2951  // optimization level and -fno-inline, not actually whether the backend has
2952  // inlining enabled.
2953  Opts.NoInlineDefine = !Opts.Optimize;
2954  if (Arg *InlineArg = Args.getLastArg(
2955  options::OPT_finline_functions, options::OPT_finline_hint_functions,
2956  options::OPT_fno_inline_functions, options::OPT_fno_inline))
2957  if (InlineArg->getOption().matches(options::OPT_fno_inline))
2958  Opts.NoInlineDefine = true;
2959 
2960  Opts.FastMath = Args.hasArg(OPT_ffast_math) ||
2961  Args.hasArg(OPT_cl_fast_relaxed_math);
2962  Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
2963  Args.hasArg(OPT_cl_finite_math_only) ||
2964  Args.hasArg(OPT_cl_fast_relaxed_math);
2965  Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
2966  Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
2967  Args.hasArg(OPT_cl_fast_relaxed_math);
2968 
2969  if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
2970  StringRef Val = A->getValue();
2971  if (Val == "fast")
2972  Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
2973  else if (Val == "on")
2974  Opts.setDefaultFPContractMode(LangOptions::FPC_On);
2975  else if (Val == "off")
2976  Opts.setDefaultFPContractMode(LangOptions::FPC_Off);
2977  else
2978  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2979  }
2980 
2981  Opts.RetainCommentsFromSystemHeaders =
2982  Args.hasArg(OPT_fretain_comments_from_system_headers);
2983 
2984  unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
2985  switch (SSP) {
2986  default:
2987  Diags.Report(diag::err_drv_invalid_value)
2988  << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
2989  break;
2990  case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
2991  case 1: Opts.setStackProtector(LangOptions::SSPOn); break;
2992  case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
2993  case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
2994  }
2995 
2996  if (Arg *A = Args.getLastArg(OPT_ftrivial_auto_var_init)) {
2997  StringRef Val = A->getValue();
2998  if (Val == "uninitialized")
2999  Opts.setTrivialAutoVarInit(
3001  else if (Val == "zero")
3002  Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Zero);
3003  else if (Val == "pattern")
3004  Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Pattern);
3005  else
3006  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3007  }
3008 
3009  // Parse -fsanitize= arguments.
3010  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3011  Diags, Opts.Sanitize);
3012  // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
3013  Opts.SanitizeAddressFieldPadding =
3014  getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
3015  Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
3016 
3017  // -fxray-instrument
3018  Opts.XRayInstrument =
3019  Args.hasFlag(OPT_fxray_instrument, OPT_fnoxray_instrument, false);
3020 
3021  // -fxray-always-emit-customevents
3022  Opts.XRayAlwaysEmitCustomEvents =
3023  Args.hasFlag(OPT_fxray_always_emit_customevents,
3024  OPT_fnoxray_always_emit_customevents, false);
3025 
3026  // -fxray-always-emit-typedevents
3027  Opts.XRayAlwaysEmitTypedEvents =
3028  Args.hasFlag(OPT_fxray_always_emit_typedevents,
3029  OPT_fnoxray_always_emit_customevents, false);
3030 
3031  // -fxray-{always,never}-instrument= filenames.
3033  Args.getAllArgValues(OPT_fxray_always_instrument);
3035  Args.getAllArgValues(OPT_fxray_never_instrument);
3036  Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list);
3037 
3038  // -fforce-emit-vtables
3039  Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
3040 
3041  // -fallow-editor-placeholders
3042  Opts.AllowEditorPlaceholders = Args.hasArg(OPT_fallow_editor_placeholders);
3043 
3044  Opts.RegisterStaticDestructors = !Args.hasArg(OPT_fno_cxx_static_destructors);
3045 
3046  if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
3047  Opts.setClangABICompat(LangOptions::ClangABI::Latest);
3048 
3049  StringRef Ver = A->getValue();
3050  std::pair<StringRef, StringRef> VerParts = Ver.split('.');
3051  unsigned Major, Minor = 0;
3052 
3053  // Check the version number is valid: either 3.x (0 <= x <= 9) or
3054  // y or y.0 (4 <= y <= current version).
3055  if (!VerParts.first.startswith("0") &&
3056  !VerParts.first.getAsInteger(10, Major) &&
3057  3 <= Major && Major <= CLANG_VERSION_MAJOR &&
3058  (Major == 3 ? VerParts.second.size() == 1 &&
3059  !VerParts.second.getAsInteger(10, Minor)
3060  : VerParts.first.size() == Ver.size() ||
3061  VerParts.second == "0")) {
3062  // Got a valid version number.
3063  if (Major == 3 && Minor <= 8)
3064  Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
3065  else if (Major <= 4)
3066  Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
3067  else if (Major <= 6)
3068  Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
3069  else if (Major <= 7)
3070  Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
3071  } else if (Ver != "latest") {
3072  Diags.Report(diag::err_drv_invalid_value)
3073  << A->getAsString(Args) << A->getValue();
3074  }
3075  }
3076 
3077  Opts.CompleteMemberPointers = Args.hasArg(OPT_fcomplete_member_pointers);
3078  Opts.BuildingPCHWithObjectFile = Args.hasArg(OPT_building_pch_with_obj);
3079 }
3080 
3082  switch (Action) {
3083  case frontend::ASTDeclList:
3084  case frontend::ASTDump:
3085  case frontend::ASTPrint:
3086  case frontend::ASTView:
3088  case frontend::EmitBC:
3089  case frontend::EmitHTML:
3090  case frontend::EmitLLVM:
3093  case frontend::EmitObj:
3094  case frontend::FixIt:
3098  case frontend::GeneratePCH:
3101  case frontend::VerifyPCH:
3103  case frontend::RewriteObjC:
3104  case frontend::RewriteTest:
3105  case frontend::RunAnalysis:
3108  return false;
3109 
3112  case frontend::DumpTokens:
3113  case frontend::InitOnly:
3118  return true;
3119  }
3120  llvm_unreachable("invalid frontend action");
3121 }
3122 
3123 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
3124  DiagnosticsEngine &Diags,
3126  Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
3127  Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
3128  Args.hasArg(OPT_pch_through_hdrstop_use);
3129  Opts.PCHWithHdrStopCreate = Args.hasArg(OPT_pch_through_hdrstop_create);
3130  Opts.PCHThroughHeader = Args.getLastArgValue(OPT_pch_through_header_EQ);
3131  Opts.UsePredefines = !Args.hasArg(OPT_undef);
3132  Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
3133  Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
3134  Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors);
3135 
3136  Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
3137  for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
3138  Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
3139 
3140  if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
3141  StringRef Value(A->getValue());
3142  size_t Comma = Value.find(',');
3143  unsigned Bytes = 0;
3144  unsigned EndOfLine = 0;
3145 
3146  if (Comma == StringRef::npos ||
3147  Value.substr(0, Comma).getAsInteger(10, Bytes) ||
3148  Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
3149  Diags.Report(diag::err_drv_preamble_format);
3150  else {
3151  Opts.PrecompiledPreambleBytes.first = Bytes;
3152  Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
3153  }
3154  }
3155 
3156  // Add the __CET__ macro if a CFProtection option is set.
3157  if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3158  StringRef Name = A->getValue();
3159  if (Name == "branch")
3160  Opts.addMacroDef("__CET__=1");
3161  else if (Name == "return")
3162  Opts.addMacroDef("__CET__=2");
3163  else if (Name == "full")
3164  Opts.addMacroDef("__CET__=3");
3165  }
3166 
3167  // Add macros from the command line.
3168  for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
3169  if (A->getOption().matches(OPT_D))
3170  Opts.addMacroDef(A->getValue());
3171  else
3172  Opts.addMacroUndef(A->getValue());
3173  }
3174 
3175  Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
3176 
3177  // Add the ordered list of -includes.
3178  for (const auto *A : Args.filtered(OPT_include))
3179  Opts.Includes.emplace_back(A->getValue());
3180 
3181  for (const auto *A : Args.filtered(OPT_chain_include))
3182  Opts.ChainedIncludes.emplace_back(A->getValue());
3183 
3184  for (const auto *A : Args.filtered(OPT_remap_file)) {
3185  std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
3186 
3187  if (Split.second.empty()) {
3188  Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
3189  continue;
3190  }
3191 
3192  Opts.addRemappedFile(Split.first, Split.second);
3193  }
3194 
3195  if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
3196  StringRef Name = A->getValue();
3197  unsigned Library = llvm::StringSwitch<unsigned>(Name)
3198  .Case("libc++", ARCXX_libcxx)
3199  .Case("libstdc++", ARCXX_libstdcxx)
3200  .Case("none", ARCXX_nolib)
3201  .Default(~0U);
3202  if (Library == ~0U)
3203  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
3204  else
3206  }
3207 
3208  // Always avoid lexing editor placeholders when we're just running the
3209  // preprocessor as we never want to emit the
3210  // "editor placeholder in source file" error in PP only mode.
3211  if (isStrictlyPreprocessorAction(Action))
3212  Opts.LexEditorPlaceholders = false;
3213 }
3214 
3216  ArgList &Args,
3218  if (isStrictlyPreprocessorAction(Action))
3219  Opts.ShowCPP = !Args.hasArg(OPT_dM);
3220  else
3221  Opts.ShowCPP = 0;
3222 
3223  Opts.ShowComments = Args.hasArg(OPT_C);
3224  Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
3225  Opts.ShowMacroComments = Args.hasArg(OPT_CC);
3226  Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
3227  Opts.ShowIncludeDirectives = Args.hasArg(OPT_dI);
3228  Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
3229  Opts.RewriteImports = Args.hasArg(OPT_frewrite_imports);
3230  Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
3231 }
3232 
3233 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
3234  DiagnosticsEngine &Diags) {
3235  Opts.CodeModel = getCodeModel(Args, Diags);
3236  Opts.ABI = Args.getLastArgValue(OPT_target_abi);
3237  if (Arg *A = Args.getLastArg(OPT_meabi)) {
3238  StringRef Value = A->getValue();
3239  llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value)
3240  .Case("default", llvm::EABI::Default)
3241  .Case("4", llvm::EABI::EABI4)
3242  .Case("5", llvm::EABI::EABI5)
3243  .Case("gnu", llvm::EABI::GNU)
3244  .Default(llvm::EABI::Unknown);
3245  if (EABIVersion == llvm::EABI::Unknown)
3246  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
3247  << Value;
3248  else
3249  Opts.EABIVersion = EABIVersion;
3250  }
3251  Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
3252  Opts.FPMath = Args.getLastArgValue(OPT_mfpmath);
3253  Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
3254  Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
3255  Opts.Triple = Args.getLastArgValue(OPT_triple);
3256  // Use the default target triple if unspecified.
3257  if (Opts.Triple.empty())
3258  Opts.Triple = llvm::sys::getDefaultTargetTriple();
3259  Opts.Triple = llvm::Triple::normalize(Opts.Triple);
3260  Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
3261  Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128);
3262  Opts.NVPTXUseShortPointers = Args.hasFlag(
3263  options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false);
3264  if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
3265  llvm::VersionTuple Version;
3266  if (Version.tryParse(A->getValue()))
3267  Diags.Report(diag::err_drv_invalid_value)
3268  << A->getAsString(Args) << A->getValue();
3269  else
3270  Opts.SDKVersion = Version;
3271  }
3272 }
3273 
3275  const char *const *ArgBegin,
3276  const char *const *ArgEnd,
3277  DiagnosticsEngine &Diags) {
3278  bool Success = true;
3279 
3280  // Parse the arguments.
3281  std::unique_ptr<OptTable> Opts = createDriverOptTable();
3282  const unsigned IncludedFlagsBitmask = options::CC1Option;
3283  unsigned MissingArgIndex, MissingArgCount;
3284  InputArgList Args =
3285  Opts->ParseArgs(llvm::makeArrayRef(ArgBegin, ArgEnd), MissingArgIndex,
3286  MissingArgCount, IncludedFlagsBitmask);
3287  LangOptions &LangOpts = *Res.getLangOpts();
3288 
3289  // Check for missing argument error.
3290  if (MissingArgCount) {
3291  Diags.Report(diag::err_drv_missing_argument)
3292  << Args.getArgString(MissingArgIndex) << MissingArgCount;
3293  Success = false;
3294  }
3295 
3296  // Issue errors on unknown arguments.
3297  for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
3298  auto ArgString = A->getAsString(Args);
3299  std::string Nearest;
3300  if (Opts->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
3301  Diags.Report(diag::err_drv_unknown_argument) << ArgString;
3302  else
3303  Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
3304  << ArgString << Nearest;
3305  Success = false;
3306  }
3307 
3308  Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
3309  Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args);
3311  Success &=
3312  ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
3313  false /*DefaultDiagColor*/, false /*DefaultShowOpt*/);
3314  ParseCommentArgs(LangOpts.CommentOpts, Args);
3316  // FIXME: We shouldn't have to pass the DashX option around here
3317  InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
3318  LangOpts.IsHeaderFile);
3319  ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
3320  Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags,
3321  Res.getTargetOpts(), Res.getFrontendOpts());
3324  llvm::Triple T(Res.getTargetOpts().Triple);
3325  if (DashX.getFormat() == InputKind::Precompiled ||
3326  DashX.getLanguage() == InputKind::LLVM_IR) {
3327  // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3328  // PassManager in BackendUtil.cpp. They need to be initializd no matter
3329  // what the input type is.
3330  if (Args.hasArg(OPT_fobjc_arc))
3331  LangOpts.ObjCAutoRefCount = 1;
3332  // PIClevel and PIELevel are needed during code generation and this should be
3333  // set regardless of the input type.
3334  LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3335  LangOpts.PIE = Args.hasArg(OPT_pic_is_pie);
3336  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3337  Diags, LangOpts.Sanitize);
3338  } else {
3339  // Other LangOpts are only initialized when the input is not AST or LLVM IR.
3340  // FIXME: Should we really be calling this for an InputKind::Asm input?
3341  ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(),
3342  Res.getPreprocessorOpts(), Diags);
3344  LangOpts.ObjCExceptions = 1;
3345  if (T.isOSDarwin() && DashX.isPreprocessed()) {
3346  // Supress the darwin-specific 'stdlibcxx-not-found' diagnostic for
3347  // preprocessed input as we don't expect it to be used with -std=libc++
3348  // anyway.
3349  Res.getDiagnosticOpts().Warnings.push_back("no-stdlibcxx-not-found");
3350  }
3351  }
3352 
3353  LangOpts.FunctionAlignment =
3354  getLastArgIntValue(Args, OPT_function_alignment, 0, Diags);
3355 
3356  if (LangOpts.CUDA) {
3357  // During CUDA device-side compilation, the aux triple is the
3358  // triple used for host compilation.
3359  if (LangOpts.CUDAIsDevice)
3361  }
3362 
3363  // Set the triple of the host for OpenMP device compile.
3364  if (LangOpts.OpenMPIsDevice)
3366 
3367  // FIXME: Override value name discarding when asan or msan is used because the
3368  // backend passes depend on the name of the alloca in order to print out
3369  // names.
3370  Res.getCodeGenOpts().DiscardValueNames &=
3371  !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3372  !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
3373  !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
3374  !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
3375 
3376  ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
3380 
3381  // Turn on -Wspir-compat for SPIR target.
3382  if (T.isSPIR())
3383  Res.getDiagnosticOpts().Warnings.push_back("spir-compat");
3384 
3385  // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
3386  if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
3387  !Res.getLangOpts()->Sanitize.empty()) {
3388  Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
3389  Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
3390  }
3391  return Success;
3392 }
3393 
3395  // Note: For QoI reasons, the things we use as a hash here should all be
3396  // dumped via the -module-info flag.
3397  using llvm::hash_code;
3398  using llvm::hash_value;
3399  using llvm::hash_combine;
3400 
3401  // Start the signature with the compiler version.
3402  // FIXME: We'd rather use something more cryptographically sound than
3403  // CityHash, but this will do for now.
3404  hash_code code = hash_value(getClangFullRepositoryVersion());
3405 
3406  // Extend the signature with the language options
3407 #define LANGOPT(Name, Bits, Default, Description) \
3408  code = hash_combine(code, LangOpts->Name);
3409 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3410  code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
3411 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
3412 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
3413 #include "clang/Basic/LangOptions.def"
3414 
3415  for (StringRef Feature : LangOpts->ModuleFeatures)
3416  code = hash_combine(code, Feature);
3417 
3418  // Extend the signature with the target options.
3419  code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
3420  TargetOpts->ABI);
3421  for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
3422  code = hash_combine(code, FeatureAsWritten);
3423 
3424  // Extend the signature with preprocessor options.
3425  const PreprocessorOptions &ppOpts = getPreprocessorOpts();
3426  const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
3427  code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
3428 
3429  for (const auto &I : getPreprocessorOpts().Macros) {
3430  // If we're supposed to ignore this macro for the purposes of modules,
3431  // don't put it into the hash.
3432  if (!hsOpts.ModulesIgnoreMacros.empty()) {
3433  // Check whether we're ignoring this macro.
3434  StringRef MacroDef = I.first;
3435  if (hsOpts.ModulesIgnoreMacros.count(
3436  llvm::CachedHashString(MacroDef.split('=').first)))
3437  continue;
3438  }
3439 
3440  code = hash_combine(code, I.first, I.second);
3441  }
3442 
3443  // Extend the signature with the sysroot and other header search options.
3444  code = hash_combine(code, hsOpts.Sysroot,
3445  hsOpts.ModuleFormat,
3446  hsOpts.UseDebugInfo,
3447  hsOpts.UseBuiltinIncludes,
3449  hsOpts.UseStandardCXXIncludes,
3450  hsOpts.UseLibcxx,
3452  code = hash_combine(code, hsOpts.ResourceDir);
3453 
3454  // Extend the signature with the user build path.
3455  code = hash_combine(code, hsOpts.ModuleUserBuildPath);
3456 
3457  // Extend the signature with the module file extensions.
3458  const FrontendOptions &frontendOpts = getFrontendOpts();
3459  for (const auto &ext : frontendOpts.ModuleFileExtensions) {
3460  code = ext->hashExtension(code);
3461  }
3462 
3463  // When compiling with -gmodules, also hash -fdebug-prefix-map as it
3464  // affects the debug info in the PCM.
3465  if (getCodeGenOpts().DebugTypeExtRefs)
3466  for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap)
3467  code = hash_combine(code, KeyValue.first, KeyValue.second);
3468 
3469  // Extend the signature with the enabled sanitizers, if at least one is
3470  // enabled. Sanitizers which cannot affect AST generation aren't hashed.
3471  SanitizerSet SanHash = LangOpts->Sanitize;
3472  SanHash.clear(getPPTransparentSanitizers());
3473  if (!SanHash.empty())
3474  code = hash_combine(code, SanHash.Mask);
3475 
3476  return llvm::APInt(64, code).toString(36, /*Signed=*/false);
3477 }
3478 
3479 template<typename IntTy>
3480 static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
3481  IntTy Default,
3482  DiagnosticsEngine *Diags) {
3483  IntTy Res = Default;
3484  if (Arg *A = Args.getLastArg(Id)) {
3485  if (StringRef(A->getValue()).getAsInteger(10, Res)) {
3486  if (Diags)
3487  Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args)
3488  << A->getValue();
3489  }
3490  }
3491  return Res;
3492 }
3493 
3494 namespace clang {
3495 
3496 // Declared in clang/Frontend/Utils.h.
3497 int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
3498  DiagnosticsEngine *Diags) {
3499  return getLastArgIntValueImpl<int>(Args, Id, Default, Diags);
3500 }
3501 
3502 uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id,
3503  uint64_t Default,
3504  DiagnosticsEngine *Diags) {
3505  return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags);
3506 }
3507 
3510  DiagnosticsEngine &Diags) {
3511  return createVFSFromCompilerInvocation(CI, Diags,
3512  llvm::vfs::getRealFileSystem());
3513 }
3514 
3516  const CompilerInvocation &CI, DiagnosticsEngine &Diags,
3518  if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
3519  return BaseFS;
3520 
3522  // earlier vfs files are on the bottom
3523  for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
3524  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
3525  Result->getBufferForFile(File);
3526  if (!Buffer) {
3527  Diags.Report(diag::err_missing_vfs_overlay_file) << File;
3528  continue;
3529  }
3530 
3531  IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
3532  std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
3533  /*DiagContext*/ nullptr, Result);
3534  if (!FS) {
3535  Diags.Report(diag::err_invalid_vfs_overlay) << File;
3536  continue;
3537  }
3538 
3539  Result = FS;
3540  }
3541  return Result;
3542 }
3543 
3544 } // namespace clang
HeaderSearchOptions & getHeaderSearchOpts()
static Visibility parseVisibility(Arg *arg, ArgList &args, DiagnosticsEngine &diags)
Attempt to parse a visibility value out of the given argument.
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
Expand macros but not #includes.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string OutputFile
The output file, if any.
bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args, DiagnosticsEngine *Diags=nullptr, bool DefaultDiagColor=true, bool DefaultShowOpt=true)
Fill out Opts based on the options given in Args.
static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args)
Enable migration to modern ObjC readwrite property.
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.
static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args)
Conform to the underlying platform&#39;s C and C++ ABIs as closely as we can.
unsigned InlineMaxStackDepth
The inlining stack depth limit.
Paths for &#39;#include <>&#39; added by &#39;-I&#39;.
std::string ModuleDependencyOutputDir
The directory to copy module dependencies to when collecting them.
std::string ObjCMTWhiteListPath
std::string DwarfDebugFlags
The string to embed in the debug information for the compile unit, if non-empty.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
std::string DOTOutputFile
The file to write GraphViz-formatted header dependencies to.
void addMacroUndef(StringRef Name)
static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, bool &IsHeaderFile)
Generate pre-compiled module from a module map.
Attempt to be ABI-compatible with code generated by Clang 6.0.x (SVN r321711).
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
unsigned IncludeBriefComments
Show brief documentation comments in code completion results.
unsigned ImplicitModuleMaps
Implicit module maps.
static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, const TargetOptions &TargetOpts, PreprocessorOptions &PPOpts, DiagnosticsEngine &Diags)
std::string SaveTempsFilePrefix
Prefix to use for -save-temps output.
Enable inferring NS_DESIGNATED_INITIALIZER for ObjC methods.
Parse and perform semantic analysis.
ObjCXXARCStandardLibraryKind
Enumerate the kinds of standard library that.
XRayInstrMask Mask
Definition: XRayInstr.h:64
std::string ModuleUserBuildPath
The directory used for a user build.
static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags)
unsigned IncludeGlobals
Show top-level decls in code completion results.
Emit a .bc file.
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:183
Format getFormat() const
Like System, but headers are implicitly wrapped in extern "C".
DependencyOutputOptions & getDependencyOutputOpts()
std::shared_ptr< HeaderSearchOptions > HeaderSearchOpts
Options controlling the #include directive.
std::shared_ptr< llvm::Regex > OptimizationRemarkMissedPattern
Regular expression to select optimizations for which we should enable missed optimization remarks...
static unsigned getOptimizationLevel(ArgList &Args, InputKind IK, DiagnosticsEngine &Diags)
static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config, StringRef OptionName, StringRef DefaultVal)
LangStandard - Information about the properties of a particular language standard.
Definition: LangStandard.h:42
static bool isBuiltinFunc(const char *Name)
Returns true if this is a libc/libm function without the &#39;__builtin_&#39; prefix.
Definition: Builtins.cpp:50
CoreFoundationABI CFRuntime
Definition: LangOptions.h:208
unsigned IncludeModuleFiles
Include module file dependencies.
void set(XRayInstrMask K, bool Value)
Definition: XRayInstr.h:53
Parse ASTs and print them.
bool hasDigraphs() const
hasDigraphs - Language supports digraphs.
Definition: LangStandard.h:97
Enable migration to NS_ENUM/NS_OPTIONS macros.
Like System, but only used for C++.
std::string HeaderIncludeOutputFile
The file to write header include output to.
StringRef P
std::vector< std::string > Includes
static bool parseDiagnosticLevelMask(StringRef FlagName, const std::vector< std::string > &Levels, DiagnosticsEngine *Diags, DiagnosticLevelMask &M)
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
std::string FPDenormalMode
The floating-point denormal mode to use.
Defines types useful for describing an Objective-C runtime.
bool isObjectiveC() const
Is the language of the input some dialect of Objective-C?
unsigned visualizeExplodedGraphWithGraphViz
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
Show all overloads.
Like System, but only used for ObjC++.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1296
static bool CreateFromArgs(CompilerInvocation &Res, const char *const *ArgBegin, const char *const *ArgEnd, DiagnosticsEngine &Diags)
Create a compiler invocation from a list of input options.
#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)
std::shared_ptr< LangOptions > LangOpts
Options controlling the language variant.
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr or CxxCtorInitializer) selects the name&#39;s to...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::vector< std::string > Reciprocals
std::vector< std::string > RewriteMapFiles
Set of files defining the rules for the symbol rewriting.
Options for controlling comment parsing.
static const LangStandard & getLangStandardForKind(Kind K)
InputKind::Language getLanguage() const
Get the language that this standard describes.
Definition: LangStandard.h:63
std::string ASTDumpFilter
If given, filter dumped AST Decl nodes by this substring.
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:36
static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, const std::string &WorkingDir)
for(auto typeArg :T->getTypeArgsAsWritten())
Options for controlling the target.
Definition: TargetOptions.h:26
llvm::SmallSetVector< llvm::CachedHashString, 16 > ModulesIgnoreMacros
The set of macro names that should be ignored for the purposes of computing the module hash...
void AddPath(StringRef Path, frontend::IncludeDirGroup Group, bool IsFramework, bool IgnoreSysRoot)
AddPath - Add the Path path to the specified Group list.
void addRemappedFile(StringRef From, StringRef To)
static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, DiagnosticsEngine *Diags)
std::string FixItSuffix
If given, the new suffix for fix-it rewritten files.
std::string HostTriple
When compiling for the device side, contains the triple used to compile for the host.
Definition: TargetOptions.h:33
std::string SplitDwarfFile
The name for the split debug info file that we&#39;ll break out.
Like System, but searched after the system directories.
BlockCommandNamesTy BlockCommandNames
Command names to treat as block commands in comments.
std::string ModuleCachePath
The directory used for the module cache.
std::string DebugPass
Enable additional debugging information.
Enable migration to modern ObjC readonly property.
float __ovld __cnfn normalize(float p)
Returns a vector in the same direction as p but with a length of 1.
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
Parse and apply any fixits to the source.
Enable migration to modern ObjC subscripting.
Defines the clang::SanitizerKind enum.
void AddSystemHeaderPrefix(StringRef Prefix, bool IsSystemHeader)
AddSystemHeaderPrefix - Override whether #include directives naming a path starting with Prefix shoul...
unsigned TimeTrace
Output time trace profile.
static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
&#39;macosx-fragile&#39; is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:39
std::map< std::string, std::string > DebugPrefixMap
std::vector< std::string > XRayAlwaysInstrumentFiles
Paths to the XRay "always instrument" files specifying which objects (files, functions, variables) should be imbued with the XRay "always instrument" attribute.
Definition: LangOptions.h:193
bool isCPlusPlus14() const
isCPlusPlus14 - Language is a C++14 variant (or later).
Definition: LangStandard.h:87
std::string FPMath
If given, the unit to use for floating point math.
Definition: TargetOptions.h:39
static std::shared_ptr< llvm::Regex > GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args, Arg *RpassArg)
Create a new Regex instance out of the string value in RpassArg.
LLVM_READONLY bool isLetter(unsigned char c)
Return true if this character is an ASCII letter: [a-zA-Z].
Definition: CharInfo.h:111
unsigned IncludeSystemHeaders
Include system header dependencies.
ShowIncludesDestination ShowIncludesDest
Destination of cl.exe style /showIncludes info.
Translate input source into HTML.
static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, DiagnosticsEngine &Diags, const TargetOptions &TargetOpts, const FrontendOptions &FrontendOpts)
Interoperability with the Swift 4.1 runtime.
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:173
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
std::string DumpExplodedGraphTo
File path to which the exploded graph should be dumped.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:49
InputKind withFormat(Format F) const
std::vector< std::string > ASTMergeFiles
The list of AST files to merge.
std::string CodeModel
The code model to use (-mcmodel).
std::vector< std::string > ModulesEmbedFiles
The list of files to embed into the compiled module file.
unsigned RelocatablePCH
When generating PCH files, instruct the AST writer to create relocatable PCH files.
Languages that the frontend can parse and compile.
Objects with "default" visibility are seen by the dynamic linker and act like normal objects...
Definition: Visibility.h:45
std::shared_ptr< PreprocessorOptions > PreprocessorOpts
Options controlling the preprocessor (aside from #include handling).
unsigned IncludeCodePatterns
Show code patterns in code completion results.
Action - Represent an abstract compilation step to perform.
Definition: Action.h:47
Generate LLVM IR, but do not emit anything.
static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
std::vector< std::string > XRayAttrListFiles
Paths to the XRay attribute list files, specifying which objects (files, functions, variables) should be imbued with the appropriate XRay attribute(s).
Definition: LangOptions.h:204
CodeGenOptions & getCodeGenOpts()
bool hasLineComments() const
Language supports &#39;//&#39; comments.
Definition: LangStandard.h:66
unsigned ShowStats
Show frontend performance metrics and statistics.
static void hash_combine(std::size_t &seed, const T &v)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts, ArgList &Args)
Emit location information but do not generate debug info in the output.
static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags)
std::vector< std::string > PassPlugins
List of dynamic shared object files to be loaded as pass plugins.
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:33
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
Enable annotation of ObjCMethods of all kinds.
bool isOpenCL() const
isOpenCL - Language is a OpenCL variant.
Definition: LangStandard.h:109
bool isCPlusPlus2a() const
isCPlusPlus2a - Language is a post-C++17 variant (or later).
Definition: LangStandard.h:93
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:148
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
Enable migration of ObjC methods to &#39;instancetype&#39;.
unsigned FixWhatYouCan
Apply fixes even if there are unfixable errors.
Defines the Diagnostic-related interfaces.
std::unique_ptr< llvm::opt::OptTable > createDriverOptTable()
std::string FullCompilerInvocation
Store full compiler invocation for reproducible instructions in the generated report.
std::vector< std::string > Warnings
The list of -W...
std::vector< std::pair< std::string, bool > > CheckersControlList
Pair of checker name and enable/disable.
unsigned DisableModuleHash
Whether we should disable the use of the hash string within the module cache.
AnalysisStores
AnalysisStores - Set of available analysis store models.
constexpr XRayInstrMask All
Definition: XRayInstr.h:41
bool isCPlusPlus() const
isCPlusPlus - Language is a C++ variant.
Definition: LangStandard.h:81
bool DisablePCHValidation
When true, disables most of the normal validation performed on precompiled headers.
Interoperability with the Swift 5.0 runtime.
VersionTuple getOpenCLVersionTuple() const
Return the OpenCL C or C++ version as a VersionTuple.
Definition: LangOptions.cpp:46
static void setPGOUseInstrumentor(CodeGenOptions &Opts, const Twine &ProfileName)
unsigned FixAndRecompile
Apply fixes and recompile.
Defines the clang::Visibility enumeration and various utility functions.
std::string FloatABI
The ABI to use for passing floating point arguments.
std::vector< std::string > ModuleFeatures
The names of any features to enable in module &#39;requires&#39; decls in addition to the hard-coded list in ...
Definition: LangOptions.h:232
PreprocessorOutputOptions & getPreprocessorOutputOpts()
std::string ThreadModel
The thread model to use.
FrontendOptions & getFrontendOpts()
std::vector< std::string > DependentLibraries
A list of dependent libraries.
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
Dump the compiler configuration.
MigratorOptions & getMigratorOpts()
Dump template instantiations.
std::string ProfileFilterFiles
Regexes separated by a semi-colon to filter the files to instrument.
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
char CoverageVersion[4]
The version string to put into coverage files.
Dump out preprocessed tokens.
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:226
const char * getName() const
getName - Get the name of this standard.
Definition: LangStandard.h:57
AnalysisDiagClients AnalysisDiagOpt
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
std::vector< std::string > ChainedIncludes
Headers that will be converted to chained PCHs in memory.
Interoperability with the ObjectiveC runtime.
void AddVFSOverlayFile(StringRef Name)
PreprocessorOutputOptions - Options for controlling the C preprocessor output (e.g., -E).
static bool IsHeaderFile(const std::string &Filename)
std::string LimitFloatPrecision
The float precision limit to use, if non-empty.
unsigned ASTDumpAll
Whether we deserialize all decls when forming AST dumps.
Generate pre-compiled module from a C++ module interface file.
prefer &#39;atomic&#39; property over &#39;nonatomic&#39;.
uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier Id, uint64_t Default, DiagnosticsEngine *Diags=nullptr)
#define LANGSTANDARD(id, name, lang, desc, features)
static void setLangDefaults(LangOptions &Opts, InputKind IK, const llvm::Triple &T, PreprocessorOptions &PPOpts, LangStandard::Kind LangStd=LangStandard::lang_unspecified)
Set language defaults for the given input language and language standard in the given LangOptions obj...
AnalysisInliningMode InliningMode
The mode of function selection used during inlining.
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:235
static std::string GetResourcesPath(const char *Argv0, void *MainAddr)
Get the directory where the compiler headers reside, relative to the compiler binary (found by the pa...
unsigned ModuleCachePruneInterval
The interval (in seconds) between pruning operations.
bool isCPlusPlus11() const
isCPlusPlus11 - Language is a C++11 variant (or later).
Definition: LangStandard.h:84
Defines the clang::LangOptions interface.
std::vector< std::string > Plugins
The list of plugins to load.
Show just the "best" overload candidates.
IncludeDirGroup
IncludeDirGroup - Identifies the group an include Entry belongs to, representing its relative positiv...
Emit only debug info necessary for generating line number tables (-gline-tables-only).
static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id, IntTy Default, DiagnosticsEngine *Diags)
int Id
Definition: ASTDiff.cpp:190
void AddPrebuiltModulePath(StringRef Name)
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
Definition: LangOptions.h:246
Defines the clang::CommentOptions interface.
std::set< std::string > DeserializedPCHDeclsToErrorOn
This is a set of names for decls that we do not want to be deserialized, and we emit an error if they...
unsigned RewriteIncludes
Preprocess include directives only.
ASTDumpOutputFormat
Used to specify the format for printing AST dump information.
unsigned ShowTimers
Show timers for individual actions.
std::string LinkerVersion
If given, the version string of the linker in use.
Definition: TargetOptions.h:48
Only execute frontend initialization.
Defines version macros and version-related utility functions for Clang.
unsigned IncludeNamespaceLevelDecls
Show decls in namespace (including the global namespace) in code completion results.
Print the "preamble" of the input file.
llvm::hash_code hash_value(const clang::SanitizerMask &Arg)
Definition: Sanitizers.cpp:51
static llvm::Reloc::Model getRelocModel(ArgList &Args, DiagnosticsEngine &Diags)
bool tryParse(StringRef input)
Try to parse an Objective-C runtime specification from the given string.
Definition: ObjCRuntime.cpp:48
bool PCHWithHdrStop
When true, we are creating or using a PCH where a #pragma hdrstop is expected to indicate the beginni...
unsigned ShowHeaderIncludes
Show header inclusions (-H).
std::shared_ptr< llvm::Regex > OptimizationRemarkPattern
Regular expression to select optimizations for which we should enable optimization remarks...
Rewriter playground.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
bool hasImplicitInt() const
hasImplicitInt - Language allows variables to be typed as int implicitly.
Definition: LangStandard.h:106
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
Definition: CharInfo.h:117
static bool IsInputCompatibleWithStandard(InputKind IK, const LangStandard &S)
Check if input file kind and language standard are compatible.
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
Definition: Sanitizers.h:167
unsigned ModulesEmbedAllFiles
Whether we should embed all used files into the PCM file.
AnalysisInliningMode
AnalysisInlineFunctionSelection - Set of inlining function selection heuristics.
Objects with "protected" visibility are seen by the dynamic linker but always dynamically resolve to ...
Definition: Visibility.h:41
unsigned ShowMacros
Print macro definitions.
bool isC2x() const
isC2x - Language is a superset of C2x.
Definition: LangStandard.h:78
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:206
static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, ArgList &Args, frontend::ActionKind Action)
static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, frontend::ActionKind Action)
unsigned FixOnlyWarnings
Apply fixes only for warnings.
unsigned ModulesValidateOncePerBuildSession
If true, skip verifying input files used by modules if the module was already verified during this bu...
bool ForceEnableInt128
If given, enables support for __int128_t and __uint128_t types.
Definition: TargetOptions.h:65
The result type of a method or function.
Attempt to be ABI-compatible with code generated by Clang 3.8.x (SVN r257626).
static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, OptSpecifier GroupWithValue, std::vector< std::string > &Diagnostics)
std::string AuxTriple
Auxiliary triple for CUDA compilation.
bool isC11() const
isC11 - Language is a superset of C11.
Definition: LangStandard.h:72
Defines the clang::XRayInstrKind enum.
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
bool AllowPCHWithCompilerErrors
When true, a PCH with compiler errors will not be rejected.
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
bool hasHexFloats() const
hasHexFloats - Language supports hexadecimal float constants.
Definition: LangStandard.h:103
unsigned ShowIncludeDirectives
Print includes, imports etc. within preprocessed output.
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
Definition: Sanitizers.h:185
unsigned ARCMTMigrateEmitARCErrors
Emit ARC errors even if the migrator can fix them.
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition: Sanitizers.h:161
static void initOption(AnalyzerOptions::ConfigTable &Config, DiagnosticsEngine *Diags, StringRef &OptionField, StringRef Name, StringRef DefaultVal)
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:42
AnalysisConstraints
AnalysisConstraints - Set of available constraint models.
llvm::StringMap< std::string > ConfigTable
AnalyzerOptionsRef getAnalyzerOpts() const
AnalysisStores AnalysisStoreOpt
InputKind getPreprocessed() const
Encodes a location in the source.
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
Generate machine code, but don&#39;t emit anything.
Assembly: we accept this only so that we can preprocess it.
std::vector< std::string > ModuleFiles
The list of additional prebuilt module files to load before processing the input. ...
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
Limit generated debug info to reduce size (-fno-standalone-debug).
Options for controlling the compiler diagnostics engine.
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
std::vector< FrontendInputFile > Inputs
The input files and their types.
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
Kind getKind() const
Definition: ObjCRuntime.h:76
unsigned ModulesValidateSystemHeaders
Whether to validate system input files when a module is loaded.
ConfigTable Config
A key-value table of use-specified configuration values.
std::string DiagnosticSerializationFile
The file to serialize diagnostics to (non-appending).
The kind of a file that we&#39;ve been handed as an input.
#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)
unsigned IncludeTimestamps
Whether timestamps should be written to the produced PCH file.
Parse ASTs and view them in Graphviz.
unsigned ShowCheckerOptionDeveloperList
std::vector< std::string > Remarks
The list of -R...
std::vector< std::string > OpenCLExtensionsAsWritten
The list of OpenCL extensions to enable or disable, as written on the command line.
Definition: TargetOptions.h:62
std::vector< std::string > DefaultFunctionAttrs
Parse ASTs and list Decl nodes.
unsigned Verbose
Whether header search information should be output as for -v.
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:89
static void getAllNoBuiltinFuncValues(ArgList &Args, std::vector< std::string > &Funcs)
bool PCHWithHdrStopCreate
When true, we are creating a PCH or creating the PCH object while expecting a #pragma hdrstop to sepa...
Defines the clang::TargetOptions class.
Enable migration to modern ObjC property.
std::unordered_map< std::string, std::vector< std::string > > PluginArgs
Args to pass to the plugins.
DiagnosticOptions & getDiagnosticOpts() const
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
unsigned ASTDumpLookups
Whether we include lookup table dumps in AST dumps.
std::vector< std::string > ExtraDeps
A list of filenames to be used as extra dependencies for every target.
Load and verify that a PCH file is usable.
std::shared_ptr< TargetOptions > TargetOpts
Options controlling the target.
std::string ModuleName
The module currently being compiled as specified by -fmodule-name.
Definition: LangOptions.h:219
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
unsigned UseLineDirectives
Use #line instead of GCC-style # N.
Like System, but only used for ObjC.
unsigned ShowVersion
Show the -version text.
unsigned RewriteImports
Include contents of transitively-imported modules.
std::shared_ptr< llvm::Regex > OptimizationRemarkAnalysisPattern
Regular expression to select optimizations for which we should enable optimization analyses...
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line...
Definition: TargetOptions.h:51
XRayInstrSet XRayInstrumentationBundle
Set of XRay instrumentation kinds to emit.
std::vector< BitcodeFileToLink > LinkBitcodeFiles
The files specified here are linked in to the module before optimizations.
constexpr XRayInstrMask None
Definition: XRayInstr.h:37
bool isUnknownAnalyzerConfig(StringRef Name) const
unsigned GenerateGlobalModuleIndex
Whether we can generate the global module index if needed.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
std::string PCHThroughHeader
If non-empty, the filename used in an #include directive in the primary source file (or command-line ...
static const StringRef GetInputKindName(InputKind IK)
Get language name for given input kind.
Enable migration to add conforming protocols.
void addMacroDef(StringRef Name)
llvm::EABI EABIVersion
The EABI version to use.
Definition: TargetOptions.h:45
&#39;#include ""&#39; paths, added by &#39;gcc -iquote&#39;.
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
std::vector< std::string > MacroIncludes
unsigned ShowHelp
Show the -help text.
std::string OverrideRecordLayoutsFile
File name of the file that will provide record layouts (in the format produced by -fdump-record-layou...
unsigned FixToTemporaries
Apply fixes to temporary files.
Like Angled, but marks system directories.
static bool parseTestModuleFileExtensionArg(StringRef Arg, std::string &BlockName, unsigned &MajorVersion, unsigned &MinorVersion, bool &Hashed, std::string &UserInfo)
Parse the argument to the -ftest-module-file-extension command-line argument.
unsigned maxBlockVisitOnPath
The maximum number of times the analyzer visits a block.
unsigned DisableAllChecks
Disable all analyzer checks.
std::string OutputFile
The file to write dependency output to.
bool allowsARC() const
Does this runtime allow ARC at all?
Definition: ObjCRuntime.h:141
ASTDumpOutputFormat ASTDumpFormat
Specifies the output format of the AST.
DependencyOutputFormat OutputFormat
The format for the dependency file.
std::string CudaGpuBinaryFileName
Name of file passed with -fcuda-include-gpubinary option to forward to CUDA runtime back-end for inco...
unsigned UseDebugInfo
Whether the module includes debug information (-gmodules).
Dataflow Directional Tag Classes.
std::string OverflowHandler
The name of the handler function to be called when -ftrapv is specified.
Definition: LangOptions.h:216
Enable migration to modern ObjC literals.
static ParsedSourceLocation FromString(StringRef Str)
Construct a parsed source location from a string; the Filename is empty on error. ...
PreprocessorOptions & getPreprocessorOpts()
Enable converting setter/getter expressions to property-dot syntx.
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
Language getLanguage() const
frontend::ActionKind ProgramAction
The frontend action to perform.
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:242
std::vector< std::string > VerifyPrefixes
The prefixes for comment directives sought by -verify ("expected" by default).
std::string ARCMTMigrateReportOut
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
std::string PreferVectorWidth
The preferred width for auto-vectorization transforms.
Emit only debug directives with the line numbers data.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
Like System, but only used for C.
bool empty() const
Returns true if no sanitizers are enabled.
Definition: Sanitizers.h:170
unsigned UseGlobalModuleIndex
Whether we can use the global module index if available.
AnalysisConstraints AnalysisConstraintsOpt
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
static bool isStrictlyPreprocessorAction(frontend::ActionKind Action)
Helper class for holding the data necessary to invoke the compiler.
std::string DebugCompilationDir
The string to embed in debug information as the current working directory.
unsigned UsePhonyTargets
Include phony targets for each dependency, which can avoid some &#39;make&#39; problems.
std::string AnalyzeSpecificFunction
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i...
Definition: LangOptions.h:250
FrontendOptions - Options for controlling the behavior of the frontend.
bool isC17() const
isC17 - Language is a superset of C17.
Definition: LangStandard.h:75
static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args)
SanitizerMask parseSanitizerValue(StringRef Value, bool AllowGroups)
Parse a single value from a -fsanitize= or -fno-sanitize= value list.
Definition: Sanitizers.cpp:27
Run a plugin action,.
bool isGNUMode() const
isGNUMode - Language includes GNU extensions.
Definition: LangStandard.h:100
std::string StatsFile
Filename to write statistics to.
Parse ASTs and dump them.
Don&#39;t generate debug info.
std::string ProfileExcludeFiles
Regexes separated by a semi-colon to filter the files to not instrument.
std::string CoverageDataFile
The filename with path we use for coverage data files.
Defines the clang::FileSystemOptions interface.
std::vector< std::string > LinkerOptions
A list of linker options to embed in the object file.
std::string RecordCommandLine
The string containing the commandline for the llvm.commandline metadata, if non-empty.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::vector< std::shared_ptr< ModuleFileExtension > > ModuleFileExtensions
The list of module file extensions.
CodeCompleteOptions CodeCompleteOpts
enum clang::FrontendOptions::@193 ARCMTAction
static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor)
IntrusiveRefCntPtr< DiagnosticOptions > DiagnosticOpts
Options controlling the diagnostic engine.
std::vector< std::string > AddPluginActions
The list of plugin actions to run in addition to the normal action.
ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary
The Objective-C++ ARC standard library that we should support, by providing appropriate definitions t...
AnalysisPurgeMode
AnalysisPurgeModes - Set of available strategies for dead symbol removal.
Stores options for the analyzer from the command line.
Keeps track of options that affect how file operations are performed.
unsigned DisableFree
Disable memory freeing on exit.
Generate pre-compiled header.
Generate pre-compiled module from a set of header files.
int getLastArgIntValue(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier Id, int Default, DiagnosticsEngine *Diags=nullptr)
Return the value of the last argument as an integer, or a default.
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:14095
unsigned ShowMacroComments
Show comments, even in macros.
bool isUnknown() const
Is the input kind fully-unknown?
Defines the clang::SourceLocation class and associated facilities.
unsigned NoRetryExhausted
Do not re-analyze paths leading to exhausted nodes with a different strategy.
Interoperability with the Swift 4.2 runtime.
std::vector< std::string > XRayNeverInstrumentFiles
Paths to the XRay "never instrument" files specifying which objects (files, functions, variables) should be imbued with the XRay "never instrument" attribute.
Definition: LangOptions.h:199
annotate property with NS_RETURNS_INNER_POINTER
bool NVPTXUseShortPointers
If enabled, use 32-bit pointers for accessing const/local/shared address space.
Definition: TargetOptions.h:69
std::string MainFileName
The user provided name for the "main file", if non-empty.
unsigned ModuleCachePruneAfter
The time (in seconds) after which an unused module file will be considered unused and will...
use NS_NONATOMIC_IOSONLY for property &#39;atomic&#39; attribute
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
Definition: LangOptions.h:238
static bool checkVerifyPrefixes(const std::vector< std::string > &VerifyPrefixes, DiagnosticsEngine *Diags)
XRayInstrMask parseXRayInstrValue(StringRef Value)
Definition: XRayInstr.cpp:18
bool isC99() const
isC99 - Language is a superset of C99.
Definition: LangStandard.h:69
unsigned IncludeFixIts
Include results after corrections (small fix-its), e.g.
unsigned ASTDumpDecls
Whether we include declaration dumps in AST dumps.
std::string ActionName
The name of the action to run when using a plugin action.
unsigned ShowLineMarkers
Show #line markers.
bool isCPlusPlus17() const
isCPlusPlus17 - Language is a C++17 variant (or later).
Definition: LangStandard.h:90
FileSystemOptions & getFileSystemOpts()
static unsigned getOptimizationLevelSize(ArgList &Args)
Run one or more source code analyses.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:152
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN)
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
std::vector< std::string > LLVMArgs
A list of arguments to forward to LLVM&#39;s option processing; this should only be used for debugging an...
std::vector< std::string > Targets
A list of names to use as the targets in the dependency file; this list must contain at least one ent...
std::string InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate, -fprofile-generate, and -fcs-profile-generate.
const char * getDescription() const
getDescription - Get the description of this standard.
Definition: LangStandard.h:60
std::string TrapFuncName
If not an empty string, trap intrinsics are lowered to calls to this function instead of to trap inst...
__DEVICE__ int max(int __a, int __b)
DiagnosticLevelMask
A bitmask representing the diagnostic levels used by VerifyDiagnosticConsumer.
Dump information about a module file.
unsigned ModuleMapFileHomeIsCwd
Set the &#39;home directory&#39; of a module map file to the current working directory (or the home directory...
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
std::string CodeModel
Definition: TargetOptions.h:75
unsigned AddMissingHeaderDeps
Add missing headers to dependency list.
std::string ThinLinkBitcodeFile
Name of a file that can optionally be written with minimized bitcode to be used as input for the Thin...
std::vector< std::string > SanitizerBlacklistFiles
Paths to blacklist files specifying which objects (files, functions, variables) should not be instrum...
Definition: LangOptions.h:187
unsigned ShowCPP
Print normal preprocessed output.
Like Angled, but marks header maps used when building frameworks.
unsigned ShouldEmitErrorsOnInvalidConfigValue
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
llvm::VersionTuple SDKVersion
The version of the SDK which was used during the compilation.
Definition: TargetOptions.h:83
static InputKind getInputKindForExtension(StringRef Extension)
getInputKindForExtension - Return the appropriate input kind for a file extension.
std::string ObjCConstantStringClass
Definition: LangOptions.h:210
#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC)
unsigned IncludeMacros
Show macros in code completion results.
AnalysisPurgeMode AnalysisPurgeOpt
static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle, ArgList &Args, DiagnosticsEngine &D, XRayInstrSet &S)
bool DumpDeserializedPCHDecls
Dump declarations that are deserialized from PCH, for testing.
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
std::map< std::string, std::string > PrebuiltModuleFiles
The mapping of module names to prebuilt module files.
AnalysisDiagClients
AnalysisDiagClients - Set of available diagnostic clients for rendering analysis results.
Attempt to be ABI-compatible with code generated by Clang 7.0.x (SVN r338536).
std::string Triple
The name of the target triple to compile for.
Definition: TargetOptions.h:29
#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC)
Defines enum values for all the target-independent builtin functions.
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
std::string ModuleFormat
The module/pch container format.
static void parseSanitizerKinds(StringRef FlagName, const std::vector< std::string > &Sanitizers, DiagnosticsEngine &Diags, SanitizerSet &S)
bool allowsWeak() const
Does this runtime allow the use of __weak?
Definition: ObjCRuntime.h:282
LangStandard::Kind Std
std::string DiagnosticLogFile
The file to log diagnostic output to.
bool ParseAllComments
Treat ordinary comments as documentation comments.
bool LexEditorPlaceholders
When enabled, the preprocessor will construct editor placeholder tokens.
std::vector< std::string > ModuleMapFiles
The list of module map files to load before processing the input.