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