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