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