xref: /freebsd/contrib/llvm-project/clang/lib/Frontend/CompilerInvocation.cpp (revision 6be3386466ab79a84b48429ae66244f21526d3df)
1 //===- CompilerInvocation.cpp ---------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/Frontend/CompilerInvocation.h"
10 #include "TestModuleFileExtension.h"
11 #include "clang/Basic/Builtins.h"
12 #include "clang/Basic/CharInfo.h"
13 #include "clang/Basic/CodeGenOptions.h"
14 #include "clang/Basic/CommentOptions.h"
15 #include "clang/Basic/DebugInfoOptions.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/DiagnosticOptions.h"
18 #include "clang/Basic/FileSystemOptions.h"
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/LangStandard.h"
22 #include "clang/Basic/ObjCRuntime.h"
23 #include "clang/Basic/Sanitizers.h"
24 #include "clang/Basic/SourceLocation.h"
25 #include "clang/Basic/TargetOptions.h"
26 #include "clang/Basic/Version.h"
27 #include "clang/Basic/Visibility.h"
28 #include "clang/Basic/XRayInstr.h"
29 #include "clang/Config/config.h"
30 #include "clang/Driver/Driver.h"
31 #include "clang/Driver/DriverDiagnostic.h"
32 #include "clang/Driver/Options.h"
33 #include "clang/Frontend/CommandLineSourceLoc.h"
34 #include "clang/Frontend/DependencyOutputOptions.h"
35 #include "clang/Frontend/FrontendDiagnostic.h"
36 #include "clang/Frontend/FrontendOptions.h"
37 #include "clang/Frontend/FrontendPluginRegistry.h"
38 #include "clang/Frontend/MigratorOptions.h"
39 #include "clang/Frontend/PreprocessorOutputOptions.h"
40 #include "clang/Frontend/Utils.h"
41 #include "clang/Lex/HeaderSearchOptions.h"
42 #include "clang/Lex/PreprocessorOptions.h"
43 #include "clang/Sema/CodeCompleteOptions.h"
44 #include "clang/Serialization/ASTBitCodes.h"
45 #include "clang/Serialization/ModuleFileExtension.h"
46 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
47 #include "llvm/ADT/APInt.h"
48 #include "llvm/ADT/ArrayRef.h"
49 #include "llvm/ADT/CachedHashString.h"
50 #include "llvm/ADT/FloatingPointMode.h"
51 #include "llvm/ADT/Hashing.h"
52 #include "llvm/ADT/None.h"
53 #include "llvm/ADT/Optional.h"
54 #include "llvm/ADT/SmallString.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/StringRef.h"
57 #include "llvm/ADT/StringSwitch.h"
58 #include "llvm/ADT/Triple.h"
59 #include "llvm/ADT/Twine.h"
60 #include "llvm/IR/DebugInfoMetadata.h"
61 #include "llvm/Linker/Linker.h"
62 #include "llvm/MC/MCTargetOptions.h"
63 #include "llvm/Option/Arg.h"
64 #include "llvm/Option/ArgList.h"
65 #include "llvm/Option/OptSpecifier.h"
66 #include "llvm/Option/OptTable.h"
67 #include "llvm/Option/Option.h"
68 #include "llvm/ProfileData/InstrProfReader.h"
69 #include "llvm/Support/CodeGen.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/Error.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/ErrorOr.h"
74 #include "llvm/Support/FileSystem.h"
75 #include "llvm/Support/Host.h"
76 #include "llvm/Support/MathExtras.h"
77 #include "llvm/Support/MemoryBuffer.h"
78 #include "llvm/Support/Path.h"
79 #include "llvm/Support/Process.h"
80 #include "llvm/Support/Regex.h"
81 #include "llvm/Support/VersionTuple.h"
82 #include "llvm/Support/VirtualFileSystem.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/Target/TargetOptions.h"
85 #include <algorithm>
86 #include <atomic>
87 #include <cassert>
88 #include <cstddef>
89 #include <cstring>
90 #include <memory>
91 #include <string>
92 #include <tuple>
93 #include <utility>
94 #include <vector>
95 
96 using namespace clang;
97 using namespace driver;
98 using namespace options;
99 using namespace llvm::opt;
100 
101 //===----------------------------------------------------------------------===//
102 // Initialization.
103 //===----------------------------------------------------------------------===//
104 
105 CompilerInvocationBase::CompilerInvocationBase()
106     : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
107       DiagnosticOpts(new DiagnosticOptions()),
108       HeaderSearchOpts(new HeaderSearchOptions()),
109       PreprocessorOpts(new PreprocessorOptions()) {}
110 
111 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
112     : LangOpts(new LangOptions(*X.getLangOpts())),
113       TargetOpts(new TargetOptions(X.getTargetOpts())),
114       DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
115       HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
116       PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
117 
118 CompilerInvocationBase::~CompilerInvocationBase() = default;
119 
120 //===----------------------------------------------------------------------===//
121 // Normalizers
122 //===----------------------------------------------------------------------===//
123 
124 #define SIMPLE_ENUM_VALUE_TABLE
125 #include "clang/Driver/Options.inc"
126 #undef SIMPLE_ENUM_VALUE_TABLE
127 
128 static llvm::Optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt,
129                                                     unsigned TableIndex,
130                                                     const ArgList &Args,
131                                                     DiagnosticsEngine &Diags) {
132   assert(TableIndex < SimpleEnumValueTablesSize);
133   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
134 
135   auto *Arg = Args.getLastArg(Opt);
136   if (!Arg)
137     return None;
138 
139   StringRef ArgValue = Arg->getValue();
140   for (int I = 0, E = Table.Size; I != E; ++I)
141     if (ArgValue == Table.Table[I].Name)
142       return Table.Table[I].Value;
143 
144   Diags.Report(diag::err_drv_invalid_value)
145       << Arg->getAsString(Args) << ArgValue;
146   return None;
147 }
148 
149 static const char *denormalizeSimpleEnum(CompilerInvocation::StringAllocator SA,
150                                          unsigned TableIndex, unsigned Value) {
151   assert(TableIndex < SimpleEnumValueTablesSize);
152   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
153   for (int I = 0, E = Table.Size; I != E; ++I)
154     if (Value == Table.Table[I].Value)
155       return Table.Table[I].Name;
156 
157   llvm_unreachable("The simple enum value was not correctly defined in "
158                    "the tablegen option description");
159 }
160 
161 static const char *denormalizeString(CompilerInvocation::StringAllocator SA,
162                                      unsigned TableIndex,
163                                      const std::string &Value) {
164   return SA(Value);
165 }
166 
167 static Optional<std::string> normalizeTriple(OptSpecifier Opt, int TableIndex,
168                                              const ArgList &Args,
169                                              DiagnosticsEngine &Diags) {
170   auto *Arg = Args.getLastArg(Opt);
171   if (!Arg)
172     return None;
173   return llvm::Triple::normalize(Arg->getValue());
174 }
175 
176 //===----------------------------------------------------------------------===//
177 // Deserialization (from args)
178 //===----------------------------------------------------------------------===//
179 
180 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
181                                      DiagnosticsEngine &Diags) {
182   unsigned DefaultOpt = llvm::CodeGenOpt::None;
183   if (IK.getLanguage() == Language::OpenCL && !Args.hasArg(OPT_cl_opt_disable))
184     DefaultOpt = llvm::CodeGenOpt::Default;
185 
186   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
187     if (A->getOption().matches(options::OPT_O0))
188       return llvm::CodeGenOpt::None;
189 
190     if (A->getOption().matches(options::OPT_Ofast))
191       return llvm::CodeGenOpt::Aggressive;
192 
193     assert(A->getOption().matches(options::OPT_O));
194 
195     StringRef S(A->getValue());
196     if (S == "s" || S == "z")
197       return llvm::CodeGenOpt::Default;
198 
199     if (S == "g")
200       return llvm::CodeGenOpt::Less;
201 
202     return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
203   }
204 
205   return DefaultOpt;
206 }
207 
208 static unsigned getOptimizationLevelSize(ArgList &Args) {
209   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
210     if (A->getOption().matches(options::OPT_O)) {
211       switch (A->getValue()[0]) {
212       default:
213         return 0;
214       case 's':
215         return 1;
216       case 'z':
217         return 2;
218       }
219     }
220   }
221   return 0;
222 }
223 
224 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
225                               OptSpecifier GroupWithValue,
226                               std::vector<std::string> &Diagnostics) {
227   for (auto *A : Args.filtered(Group)) {
228     if (A->getOption().getKind() == Option::FlagClass) {
229       // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
230       // its name (minus the "W" or "R" at the beginning) to the warning list.
231       Diagnostics.push_back(
232           std::string(A->getOption().getName().drop_front(1)));
233     } else if (A->getOption().matches(GroupWithValue)) {
234       // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group.
235       Diagnostics.push_back(
236           std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
237     } else {
238       // Otherwise, add its value (for OPT_W_Joined and similar).
239       for (const auto *Arg : A->getValues())
240         Diagnostics.emplace_back(Arg);
241     }
242   }
243 }
244 
245 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
246 // it won't verify the input.
247 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
248                                  DiagnosticsEngine *Diags);
249 
250 static void getAllNoBuiltinFuncValues(ArgList &Args,
251                                       std::vector<std::string> &Funcs) {
252   SmallVector<const char *, 8> Values;
253   for (const auto &Arg : Args) {
254     const Option &O = Arg->getOption();
255     if (O.matches(options::OPT_fno_builtin_)) {
256       const char *FuncName = Arg->getValue();
257       if (Builtin::Context::isBuiltinFunc(FuncName))
258         Values.push_back(FuncName);
259     }
260   }
261   Funcs.insert(Funcs.end(), Values.begin(), Values.end());
262 }
263 
264 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
265                               DiagnosticsEngine &Diags) {
266   bool Success = true;
267   if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
268     StringRef Name = A->getValue();
269     AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
270 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
271       .Case(CMDFLAG, NAME##Model)
272 #include "clang/StaticAnalyzer/Core/Analyses.def"
273       .Default(NumStores);
274     if (Value == NumStores) {
275       Diags.Report(diag::err_drv_invalid_value)
276         << A->getAsString(Args) << Name;
277       Success = false;
278     } else {
279       Opts.AnalysisStoreOpt = Value;
280     }
281   }
282 
283   if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
284     StringRef Name = A->getValue();
285     AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
286 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
287       .Case(CMDFLAG, NAME##Model)
288 #include "clang/StaticAnalyzer/Core/Analyses.def"
289       .Default(NumConstraints);
290     if (Value == NumConstraints) {
291       Diags.Report(diag::err_drv_invalid_value)
292         << A->getAsString(Args) << Name;
293       Success = false;
294     } else {
295       Opts.AnalysisConstraintsOpt = Value;
296     }
297   }
298 
299   if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
300     StringRef Name = A->getValue();
301     AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
302 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
303       .Case(CMDFLAG, PD_##NAME)
304 #include "clang/StaticAnalyzer/Core/Analyses.def"
305       .Default(NUM_ANALYSIS_DIAG_CLIENTS);
306     if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
307       Diags.Report(diag::err_drv_invalid_value)
308         << A->getAsString(Args) << Name;
309       Success = false;
310     } else {
311       Opts.AnalysisDiagOpt = Value;
312     }
313   }
314 
315   if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
316     StringRef Name = A->getValue();
317     AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
318 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
319       .Case(CMDFLAG, NAME)
320 #include "clang/StaticAnalyzer/Core/Analyses.def"
321       .Default(NumPurgeModes);
322     if (Value == NumPurgeModes) {
323       Diags.Report(diag::err_drv_invalid_value)
324         << A->getAsString(Args) << Name;
325       Success = false;
326     } else {
327       Opts.AnalysisPurgeOpt = Value;
328     }
329   }
330 
331   if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
332     StringRef Name = A->getValue();
333     AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
334 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
335       .Case(CMDFLAG, NAME)
336 #include "clang/StaticAnalyzer/Core/Analyses.def"
337       .Default(NumInliningModes);
338     if (Value == NumInliningModes) {
339       Diags.Report(diag::err_drv_invalid_value)
340         << A->getAsString(Args) << Name;
341       Success = false;
342     } else {
343       Opts.InliningMode = Value;
344     }
345   }
346 
347   Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
348   Opts.ShowCheckerHelpAlpha = Args.hasArg(OPT_analyzer_checker_help_alpha);
349   Opts.ShowCheckerHelpDeveloper =
350       Args.hasArg(OPT_analyzer_checker_help_developer);
351 
352   Opts.ShowCheckerOptionList = Args.hasArg(OPT_analyzer_checker_option_help);
353   Opts.ShowCheckerOptionAlphaList =
354       Args.hasArg(OPT_analyzer_checker_option_help_alpha);
355   Opts.ShowCheckerOptionDeveloperList =
356       Args.hasArg(OPT_analyzer_checker_option_help_developer);
357 
358   Opts.ShowConfigOptionsList = Args.hasArg(OPT_analyzer_config_help);
359   Opts.ShowEnabledCheckerList = Args.hasArg(OPT_analyzer_list_enabled_checkers);
360   Opts.ShouldEmitErrorsOnInvalidConfigValue =
361       /* negated */!llvm::StringSwitch<bool>(
362                    Args.getLastArgValue(OPT_analyzer_config_compatibility_mode))
363         .Case("true", true)
364         .Case("false", false)
365         .Default(false);
366   Opts.DisableAllCheckers = Args.hasArg(OPT_analyzer_disable_all_checks);
367 
368   Opts.visualizeExplodedGraphWithGraphViz =
369     Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
370   Opts.DumpExplodedGraphTo =
371       std::string(Args.getLastArgValue(OPT_analyzer_dump_egraph));
372   Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
373   Opts.AnalyzerWerror = Args.hasArg(OPT_analyzer_werror);
374   Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
375   Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
376   Opts.AnalyzeNestedBlocks =
377     Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
378   Opts.AnalyzeSpecificFunction =
379       std::string(Args.getLastArgValue(OPT_analyze_function));
380   Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
381   Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
382   Opts.maxBlockVisitOnPath =
383       getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags);
384   Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
385   Opts.InlineMaxStackDepth =
386       getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
387                          Opts.InlineMaxStackDepth, Diags);
388 
389   Opts.CheckersAndPackages.clear();
390   for (const Arg *A :
391        Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
392     A->claim();
393     bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
394     // We can have a list of comma separated checker names, e.g:
395     // '-analyzer-checker=cocoa,unix'
396     StringRef CheckerAndPackageList = A->getValue();
397     SmallVector<StringRef, 16> CheckersAndPackages;
398     CheckerAndPackageList.split(CheckersAndPackages, ",");
399     for (const StringRef &CheckerOrPackage : CheckersAndPackages)
400       Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
401                                             IsEnabled);
402   }
403 
404   // Go through the analyzer configuration options.
405   for (const auto *A : Args.filtered(OPT_analyzer_config)) {
406 
407     // We can have a list of comma separated config names, e.g:
408     // '-analyzer-config key1=val1,key2=val2'
409     StringRef configList = A->getValue();
410     SmallVector<StringRef, 4> configVals;
411     configList.split(configVals, ",");
412     for (const auto &configVal : configVals) {
413       StringRef key, val;
414       std::tie(key, val) = configVal.split("=");
415       if (val.empty()) {
416         Diags.Report(SourceLocation(),
417                      diag::err_analyzer_config_no_value) << configVal;
418         Success = false;
419         break;
420       }
421       if (val.find('=') != StringRef::npos) {
422         Diags.Report(SourceLocation(),
423                      diag::err_analyzer_config_multiple_values)
424           << configVal;
425         Success = false;
426         break;
427       }
428 
429       // TODO: Check checker options too, possibly in CheckerRegistry.
430       // Leave unknown non-checker configs unclaimed.
431       if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
432         if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
433           Diags.Report(diag::err_analyzer_config_unknown) << key;
434         continue;
435       }
436 
437       A->claim();
438       Opts.Config[key] = std::string(val);
439     }
440   }
441 
442   if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
443     parseAnalyzerConfigs(Opts, &Diags);
444   else
445     parseAnalyzerConfigs(Opts, nullptr);
446 
447   llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
448   for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
449     if (i != 0)
450       os << " ";
451     os << Args.getArgString(i);
452   }
453   os.flush();
454 
455   return Success;
456 }
457 
458 static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
459                                  StringRef OptionName, StringRef DefaultVal) {
460   return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
461 }
462 
463 static void initOption(AnalyzerOptions::ConfigTable &Config,
464                        DiagnosticsEngine *Diags,
465                        StringRef &OptionField, StringRef Name,
466                        StringRef DefaultVal) {
467   // String options may be known to invalid (e.g. if the expected string is a
468   // file name, but the file does not exist), those will have to be checked in
469   // parseConfigs.
470   OptionField = getStringOption(Config, Name, DefaultVal);
471 }
472 
473 static void initOption(AnalyzerOptions::ConfigTable &Config,
474                        DiagnosticsEngine *Diags,
475                        bool &OptionField, StringRef Name, bool DefaultVal) {
476   auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>(
477                  getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
478       .Case("true", true)
479       .Case("false", false)
480       .Default(None);
481 
482   if (!PossiblyInvalidVal) {
483     if (Diags)
484       Diags->Report(diag::err_analyzer_config_invalid_input)
485         << Name << "a boolean";
486     else
487       OptionField = DefaultVal;
488   } else
489     OptionField = PossiblyInvalidVal.getValue();
490 }
491 
492 static void initOption(AnalyzerOptions::ConfigTable &Config,
493                        DiagnosticsEngine *Diags,
494                        unsigned &OptionField, StringRef Name,
495                        unsigned DefaultVal) {
496 
497   OptionField = DefaultVal;
498   bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
499                      .getAsInteger(0, OptionField);
500   if (Diags && HasFailed)
501     Diags->Report(diag::err_analyzer_config_invalid_input)
502       << Name << "an unsigned";
503 }
504 
505 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
506                                  DiagnosticsEngine *Diags) {
507   // TODO: There's no need to store the entire configtable, it'd be plenty
508   // enough tostore checker options.
509 
510 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL)                \
511   initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
512 
513 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC,        \
514                                            SHALLOW_VAL, DEEP_VAL)              \
515   switch (AnOpts.getUserMode()) {                                              \
516   case UMK_Shallow:                                                            \
517     initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL);       \
518     break;                                                                     \
519   case UMK_Deep:                                                               \
520     initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL);          \
521     break;                                                                     \
522   }                                                                            \
523 
524 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
525 #undef ANALYZER_OPTION
526 #undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
527 
528   // At this point, AnalyzerOptions is configured. Let's validate some options.
529 
530   // FIXME: Here we try to validate the silenced checkers or packages are valid.
531   // The current approach only validates the registered checkers which does not
532   // contain the runtime enabled checkers and optimally we would validate both.
533   if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
534     std::vector<StringRef> Checkers =
535         AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
536     std::vector<StringRef> Packages =
537         AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
538 
539     SmallVector<StringRef, 16> CheckersAndPackages;
540     AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
541 
542     for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
543       if (Diags) {
544         bool IsChecker = CheckerOrPackage.contains('.');
545         bool IsValidName =
546             IsChecker
547                 ? llvm::find(Checkers, CheckerOrPackage) != Checkers.end()
548                 : llvm::find(Packages, CheckerOrPackage) != Packages.end();
549 
550         if (!IsValidName)
551           Diags->Report(diag::err_unknown_analyzer_checker_or_package)
552               << CheckerOrPackage;
553       }
554 
555       AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
556     }
557   }
558 
559   if (!Diags)
560     return;
561 
562   if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
563     Diags->Report(diag::err_analyzer_config_invalid_input)
564         << "track-conditions-debug" << "'track-conditions' to also be enabled";
565 
566   if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
567     Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
568                                                            << "a filename";
569 
570   if (!AnOpts.ModelPath.empty() &&
571       !llvm::sys::fs::is_directory(AnOpts.ModelPath))
572     Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
573                                                            << "a filename";
574 }
575 
576 static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
577   Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error);
578   Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal);
579   return true;
580 }
581 
582 static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
583   Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
584   Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
585 }
586 
587 /// Create a new Regex instance out of the string value in \p RpassArg.
588 /// It returns a pointer to the newly generated Regex instance.
589 static std::shared_ptr<llvm::Regex>
590 GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args,
591                                 Arg *RpassArg) {
592   StringRef Val = RpassArg->getValue();
593   std::string RegexError;
594   std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val);
595   if (!Pattern->isValid(RegexError)) {
596     Diags.Report(diag::err_drv_optimization_remark_pattern)
597         << RegexError << RpassArg->getAsString(Args);
598     Pattern.reset();
599   }
600   return Pattern;
601 }
602 
603 static bool parseDiagnosticLevelMask(StringRef FlagName,
604                                      const std::vector<std::string> &Levels,
605                                      DiagnosticsEngine *Diags,
606                                      DiagnosticLevelMask &M) {
607   bool Success = true;
608   for (const auto &Level : Levels) {
609     DiagnosticLevelMask const PM =
610       llvm::StringSwitch<DiagnosticLevelMask>(Level)
611         .Case("note",    DiagnosticLevelMask::Note)
612         .Case("remark",  DiagnosticLevelMask::Remark)
613         .Case("warning", DiagnosticLevelMask::Warning)
614         .Case("error",   DiagnosticLevelMask::Error)
615         .Default(DiagnosticLevelMask::None);
616     if (PM == DiagnosticLevelMask::None) {
617       Success = false;
618       if (Diags)
619         Diags->Report(diag::err_drv_invalid_value) << FlagName << Level;
620     }
621     M = M | PM;
622   }
623   return Success;
624 }
625 
626 static void parseSanitizerKinds(StringRef FlagName,
627                                 const std::vector<std::string> &Sanitizers,
628                                 DiagnosticsEngine &Diags, SanitizerSet &S) {
629   for (const auto &Sanitizer : Sanitizers) {
630     SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
631     if (K == SanitizerMask())
632       Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
633     else
634       S.set(K, true);
635   }
636 }
637 
638 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
639                                            ArgList &Args, DiagnosticsEngine &D,
640                                            XRayInstrSet &S) {
641   llvm::SmallVector<StringRef, 2> BundleParts;
642   llvm::SplitString(Bundle, BundleParts, ",");
643   for (const auto &B : BundleParts) {
644     auto Mask = parseXRayInstrValue(B);
645     if (Mask == XRayInstrKind::None)
646       if (B != "none")
647         D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
648       else
649         S.Mask = Mask;
650     else if (Mask == XRayInstrKind::All)
651       S.Mask = Mask;
652     else
653       S.set(Mask, true);
654   }
655 }
656 
657 // Set the profile kind for fprofile-instrument.
658 static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args,
659                                DiagnosticsEngine &Diags) {
660   Arg *A = Args.getLastArg(OPT_fprofile_instrument_EQ);
661   if (A == nullptr)
662     return;
663   StringRef S = A->getValue();
664   unsigned I = llvm::StringSwitch<unsigned>(S)
665                    .Case("none", CodeGenOptions::ProfileNone)
666                    .Case("clang", CodeGenOptions::ProfileClangInstr)
667                    .Case("llvm", CodeGenOptions::ProfileIRInstr)
668                    .Case("csllvm", CodeGenOptions::ProfileCSIRInstr)
669                    .Default(~0U);
670   if (I == ~0U) {
671     Diags.Report(diag::err_drv_invalid_pgo_instrumentor) << A->getAsString(Args)
672                                                          << S;
673     return;
674   }
675   auto Instrumentor = static_cast<CodeGenOptions::ProfileInstrKind>(I);
676   Opts.setProfileInstr(Instrumentor);
677 }
678 
679 // Set the profile kind using fprofile-instrument-use-path.
680 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
681                                   const Twine &ProfileName) {
682   auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
683   // In error, return silently and let Clang PGOUse report the error message.
684   if (auto E = ReaderOrErr.takeError()) {
685     llvm::consumeError(std::move(E));
686     Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
687     return;
688   }
689   std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
690     std::move(ReaderOrErr.get());
691   if (PGOReader->isIRLevelProfile()) {
692     if (PGOReader->hasCSIRLevelProfile())
693       Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
694     else
695       Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
696   } else
697     Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
698 }
699 
700 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
701                              DiagnosticsEngine &Diags,
702                              const TargetOptions &TargetOpts,
703                              const FrontendOptions &FrontendOpts) {
704   bool Success = true;
705   llvm::Triple Triple = llvm::Triple(TargetOpts.Triple);
706 
707   unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
708   // TODO: This could be done in Driver
709   unsigned MaxOptLevel = 3;
710   if (OptimizationLevel > MaxOptLevel) {
711     // If the optimization level is not supported, fall back on the default
712     // optimization
713     Diags.Report(diag::warn_drv_optimization_value)
714         << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
715     OptimizationLevel = MaxOptLevel;
716   }
717   Opts.OptimizationLevel = OptimizationLevel;
718 
719   // At O0 we want to fully disable inlining outside of cases marked with
720   // 'alwaysinline' that are required for correctness.
721   Opts.setInlining((Opts.OptimizationLevel == 0)
722                        ? CodeGenOptions::OnlyAlwaysInlining
723                        : CodeGenOptions::NormalInlining);
724   // Explicit inlining flags can disable some or all inlining even at
725   // optimization levels above zero.
726   if (Arg *InlineArg = Args.getLastArg(
727           options::OPT_finline_functions, options::OPT_finline_hint_functions,
728           options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
729     if (Opts.OptimizationLevel > 0) {
730       const Option &InlineOpt = InlineArg->getOption();
731       if (InlineOpt.matches(options::OPT_finline_functions))
732         Opts.setInlining(CodeGenOptions::NormalInlining);
733       else if (InlineOpt.matches(options::OPT_finline_hint_functions))
734         Opts.setInlining(CodeGenOptions::OnlyHintInlining);
735       else
736         Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
737     }
738   }
739 
740   Opts.ExperimentalNewPassManager = Args.hasFlag(
741       OPT_fexperimental_new_pass_manager, OPT_fno_experimental_new_pass_manager,
742       /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER);
743 
744   Opts.DebugPassManager =
745       Args.hasFlag(OPT_fdebug_pass_manager, OPT_fno_debug_pass_manager,
746                    /* Default */ false);
747 
748   if (Arg *A = Args.getLastArg(OPT_fveclib)) {
749     StringRef Name = A->getValue();
750     if (Name == "Accelerate")
751       Opts.setVecLib(CodeGenOptions::Accelerate);
752     else if (Name == "MASSV")
753       Opts.setVecLib(CodeGenOptions::MASSV);
754     else if (Name == "SVML")
755       Opts.setVecLib(CodeGenOptions::SVML);
756     else if (Name == "none")
757       Opts.setVecLib(CodeGenOptions::NoLibrary);
758     else
759       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
760   }
761 
762   if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
763     unsigned Val =
764         llvm::StringSwitch<unsigned>(A->getValue())
765             .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
766             .Case("line-directives-only", codegenoptions::DebugDirectivesOnly)
767             .Case("constructor", codegenoptions::DebugInfoConstructor)
768             .Case("limited", codegenoptions::LimitedDebugInfo)
769             .Case("standalone", codegenoptions::FullDebugInfo)
770             .Default(~0U);
771     if (Val == ~0U)
772       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
773                                                 << A->getValue();
774     else
775       Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
776   }
777   if (Arg *A = Args.getLastArg(OPT_debugger_tuning_EQ)) {
778     unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
779                        .Case("gdb", unsigned(llvm::DebuggerKind::GDB))
780                        .Case("lldb", unsigned(llvm::DebuggerKind::LLDB))
781                        .Case("sce", unsigned(llvm::DebuggerKind::SCE))
782                        .Default(~0U);
783     if (Val == ~0U)
784       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
785                                                 << A->getValue();
786     else
787       Opts.setDebuggerTuning(static_cast<llvm::DebuggerKind>(Val));
788   }
789   Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 0, Diags);
790   Opts.DebugColumnInfo = !Args.hasArg(OPT_gno_column_info);
791   Opts.EmitCodeView = Args.hasArg(OPT_gcodeview);
792   Opts.CodeViewGHash = Args.hasArg(OPT_gcodeview_ghash);
793   Opts.MacroDebugInfo = Args.hasArg(OPT_debug_info_macro);
794   Opts.WholeProgramVTables = Args.hasArg(OPT_fwhole_program_vtables);
795   Opts.VirtualFunctionElimination =
796       Args.hasArg(OPT_fvirtual_function_elimination);
797   Opts.LTOVisibilityPublicStd = Args.hasArg(OPT_flto_visibility_public_std);
798   Opts.SplitDwarfFile = std::string(Args.getLastArgValue(OPT_split_dwarf_file));
799   Opts.SplitDwarfOutput =
800       std::string(Args.getLastArgValue(OPT_split_dwarf_output));
801   Opts.SplitDwarfInlining = !Args.hasArg(OPT_fno_split_dwarf_inlining);
802   Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs);
803   Opts.DebugExplicitImport = Args.hasArg(OPT_dwarf_explicit_import);
804   Opts.DebugFwdTemplateParams = Args.hasArg(OPT_debug_forward_template_params);
805   Opts.EmbedSource = Args.hasArg(OPT_gembed_source);
806   Opts.ForceDwarfFrameSection = Args.hasArg(OPT_fforce_dwarf_frame);
807 
808   for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
809     auto Split = StringRef(Arg).split('=');
810     Opts.DebugPrefixMap.insert(
811         {std::string(Split.first), std::string(Split.second)});
812   }
813 
814   if (const Arg *A =
815           Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists))
816     Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists;
817 
818   Opts.DisableLLVMPasses = Args.hasArg(OPT_disable_llvm_passes);
819   Opts.DisableLifetimeMarkers = Args.hasArg(OPT_disable_lifetimemarkers);
820 
821   const llvm::Triple::ArchType DebugEntryValueArchs[] = {
822       llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
823       llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
824       llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
825 
826   llvm::Triple T(TargetOpts.Triple);
827   if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
828       llvm::is_contained(DebugEntryValueArchs, T.getArch()))
829     Opts.EmitCallSiteInfo = true;
830 
831   Opts.DisableO0ImplyOptNone = Args.hasArg(OPT_disable_O0_optnone);
832   Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
833   Opts.IndirectTlsSegRefs = Args.hasArg(OPT_mno_tls_direct_seg_refs);
834   Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
835   Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
836     OPT_fuse_register_sized_bitfield_access);
837   Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
838   Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa);
839   Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
840                            Args.hasArg(OPT_new_struct_path_tbaa);
841   Opts.FineGrainedBitfieldAccesses =
842       Args.hasFlag(OPT_ffine_grained_bitfield_accesses,
843                    OPT_fno_fine_grained_bitfield_accesses, false);
844   Opts.DwarfDebugFlags =
845       std::string(Args.getLastArgValue(OPT_dwarf_debug_flags));
846   Opts.RecordCommandLine =
847       std::string(Args.getLastArgValue(OPT_record_command_line));
848   Opts.MergeAllConstants = Args.hasArg(OPT_fmerge_all_constants);
849   Opts.NoCommon = !Args.hasArg(OPT_fcommon);
850   Opts.NoInlineLineTables = Args.hasArg(OPT_gno_inline_line_tables);
851   Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
852   Opts.OptimizeSize = getOptimizationLevelSize(Args);
853   Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
854                             Args.hasArg(OPT_ffreestanding));
855   if (Opts.SimplifyLibCalls)
856     getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
857   Opts.UnrollLoops =
858       Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
859                    (Opts.OptimizationLevel > 1));
860   Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
861 
862   Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
863   Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
864   Opts.SampleProfileFile =
865       std::string(Args.getLastArgValue(OPT_fprofile_sample_use_EQ));
866   Opts.DebugInfoForProfiling = Args.hasFlag(
867       OPT_fdebug_info_for_profiling, OPT_fno_debug_info_for_profiling, false);
868   Opts.DebugNameTable = static_cast<unsigned>(
869       Args.hasArg(OPT_ggnu_pubnames)
870           ? llvm::DICompileUnit::DebugNameTableKind::GNU
871           : Args.hasArg(OPT_gpubnames)
872                 ? llvm::DICompileUnit::DebugNameTableKind::Default
873                 : llvm::DICompileUnit::DebugNameTableKind::None);
874   Opts.DebugRangesBaseAddress = Args.hasArg(OPT_fdebug_ranges_base_address);
875 
876   setPGOInstrumentor(Opts, Args, Diags);
877   Opts.InstrProfileOutput =
878       std::string(Args.getLastArgValue(OPT_fprofile_instrument_path_EQ));
879   Opts.ProfileInstrumentUsePath =
880       std::string(Args.getLastArgValue(OPT_fprofile_instrument_use_path_EQ));
881   if (!Opts.ProfileInstrumentUsePath.empty())
882     setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
883   Opts.ProfileRemappingFile =
884       std::string(Args.getLastArgValue(OPT_fprofile_remapping_file_EQ));
885   if (!Opts.ProfileRemappingFile.empty() && !Opts.ExperimentalNewPassManager) {
886     Diags.Report(diag::err_drv_argument_only_allowed_with)
887       << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
888       << "-fexperimental-new-pass-manager";
889   }
890 
891   Opts.CoverageMapping =
892       Args.hasFlag(OPT_fcoverage_mapping, OPT_fno_coverage_mapping, false);
893   Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping);
894   Opts.AsmVerbose = !Args.hasArg(OPT_fno_verbose_asm);
895   Opts.PreserveAsmComments = !Args.hasArg(OPT_fno_preserve_as_comments);
896   Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
897   Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
898   Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
899   Opts.RegisterGlobalDtorsWithAtExit =
900       Args.hasArg(OPT_fregister_global_dtors_with_atexit);
901   Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
902   Opts.CodeModel = TargetOpts.CodeModel;
903   Opts.DebugPass = std::string(Args.getLastArgValue(OPT_mdebug_pass));
904 
905   // Handle -mframe-pointer option.
906   if (Arg *A = Args.getLastArg(OPT_mframe_pointer_EQ)) {
907     CodeGenOptions::FramePointerKind FP;
908     StringRef Name = A->getValue();
909     bool ValidFP = true;
910     if (Name == "none")
911       FP = CodeGenOptions::FramePointerKind::None;
912     else if (Name == "non-leaf")
913       FP = CodeGenOptions::FramePointerKind::NonLeaf;
914     else if (Name == "all")
915       FP = CodeGenOptions::FramePointerKind::All;
916     else {
917       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
918       Success = false;
919       ValidFP = false;
920     }
921     if (ValidFP)
922       Opts.setFramePointer(FP);
923   }
924 
925   Opts.DisableFree = Args.hasArg(OPT_disable_free);
926   Opts.DiscardValueNames = Args.hasArg(OPT_discard_value_names);
927   Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
928   Opts.NoEscapingBlockTailCalls =
929       Args.hasArg(OPT_fno_escaping_block_tail_calls);
930   Opts.FloatABI = std::string(Args.getLastArgValue(OPT_mfloat_abi));
931   Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable) ||
932                           Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
933                           Args.hasArg(OPT_cl_fast_relaxed_math);
934   Opts.LimitFloatPrecision =
935       std::string(Args.getLastArgValue(OPT_mlimit_float_precision));
936   Opts.CorrectlyRoundedDivSqrt =
937       Args.hasArg(OPT_cl_fp32_correctly_rounded_divide_sqrt);
938   Opts.UniformWGSize =
939       Args.hasArg(OPT_cl_uniform_work_group_size);
940   Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
941   Opts.StrictFloatCastOverflow =
942       !Args.hasArg(OPT_fno_strict_float_cast_overflow);
943 
944   Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_fno_zero_initialized_in_bss);
945   Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
946   Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
947   Opts.SmallDataLimit =
948       getLastArgIntValue(Args, OPT_msmall_data_limit, 0, Diags);
949   Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
950   Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn);
951   Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
952   Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
953   Opts.IncrementalLinkerCompatible =
954       Args.hasArg(OPT_mincremental_linker_compatible);
955   Opts.PIECopyRelocations =
956       Args.hasArg(OPT_mpie_copy_relocations);
957   Opts.NoPLT = Args.hasArg(OPT_fno_plt);
958   Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
959   Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
960   Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
961   Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
962   Opts.StrictReturn = !Args.hasArg(OPT_fno_strict_return);
963   Opts.StrictVTablePointers = Args.hasArg(OPT_fstrict_vtable_pointers);
964   Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
965   Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
966   Opts.ThreadModel =
967       std::string(Args.getLastArgValue(OPT_mthread_model, "posix"));
968   if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single")
969     Diags.Report(diag::err_drv_invalid_value)
970         << Args.getLastArg(OPT_mthread_model)->getAsString(Args)
971         << Opts.ThreadModel;
972   Opts.TrapFuncName = std::string(Args.getLastArgValue(OPT_ftrap_function_EQ));
973   Opts.UseInitArray = !Args.hasArg(OPT_fno_use_init_array);
974 
975   Opts.BBSections =
976       std::string(Args.getLastArgValue(OPT_fbasic_block_sections_EQ, "none"));
977 
978   // Basic Block Sections implies Function Sections.
979   Opts.FunctionSections =
980       Args.hasArg(OPT_ffunction_sections) ||
981       (Opts.BBSections != "none" && Opts.BBSections != "labels");
982 
983   Opts.DataSections = Args.hasArg(OPT_fdata_sections);
984   Opts.StackSizeSection = Args.hasArg(OPT_fstack_size_section);
985   Opts.UniqueSectionNames = !Args.hasArg(OPT_fno_unique_section_names);
986   Opts.UniqueBasicBlockSectionNames =
987       Args.hasArg(OPT_funique_basic_block_section_names);
988   Opts.UniqueInternalLinkageNames =
989       Args.hasArg(OPT_funique_internal_linkage_names);
990 
991   Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
992 
993   Opts.NoUseJumpTables = Args.hasArg(OPT_fno_jump_tables);
994 
995   Opts.NullPointerIsValid = Args.hasArg(OPT_fno_delete_null_pointer_checks);
996 
997   Opts.ProfileSampleAccurate = Args.hasArg(OPT_fprofile_sample_accurate);
998 
999   Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
1000   Opts.PrepareForThinLTO = false;
1001   if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
1002     StringRef S = A->getValue();
1003     if (S == "thin")
1004       Opts.PrepareForThinLTO = true;
1005     else if (S != "full")
1006       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
1007   }
1008   Opts.LTOUnit = Args.hasFlag(OPT_flto_unit, OPT_fno_lto_unit, false);
1009   Opts.EnableSplitLTOUnit = Args.hasArg(OPT_fsplit_lto_unit);
1010   if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
1011     if (IK.getLanguage() != Language::LLVM_IR)
1012       Diags.Report(diag::err_drv_argument_only_allowed_with)
1013           << A->getAsString(Args) << "-x ir";
1014     Opts.ThinLTOIndexFile =
1015         std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
1016   }
1017   if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
1018     Opts.SaveTempsFilePrefix =
1019         llvm::StringSwitch<std::string>(A->getValue())
1020             .Case("obj", FrontendOpts.OutputFile)
1021             .Default(llvm::sys::path::filename(FrontendOpts.OutputFile).str());
1022 
1023   Opts.ThinLinkBitcodeFile =
1024       std::string(Args.getLastArgValue(OPT_fthin_link_bitcode_EQ));
1025 
1026   Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
1027 
1028   Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
1029   Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
1030 
1031   Opts.PreferVectorWidth =
1032       std::string(Args.getLastArgValue(OPT_mprefer_vector_width_EQ));
1033 
1034   Opts.MainFileName = std::string(Args.getLastArgValue(OPT_main_file_name));
1035   Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
1036 
1037   Opts.ControlFlowGuardNoChecks = Args.hasArg(OPT_cfguard_no_checks);
1038   Opts.ControlFlowGuard = Args.hasArg(OPT_cfguard);
1039 
1040   Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
1041   Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
1042   Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
1043   if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
1044     Opts.CoverageDataFile =
1045         std::string(Args.getLastArgValue(OPT_coverage_data_file));
1046     Opts.CoverageNotesFile =
1047         std::string(Args.getLastArgValue(OPT_coverage_notes_file));
1048     Opts.ProfileFilterFiles =
1049         std::string(Args.getLastArgValue(OPT_fprofile_filter_files_EQ));
1050     Opts.ProfileExcludeFiles =
1051         std::string(Args.getLastArgValue(OPT_fprofile_exclude_files_EQ));
1052     if (Args.hasArg(OPT_coverage_version_EQ)) {
1053       StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
1054       if (CoverageVersion.size() != 4) {
1055         Diags.Report(diag::err_drv_invalid_value)
1056             << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
1057             << CoverageVersion;
1058       } else {
1059         memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
1060       }
1061     }
1062   }
1063   // Handle -fembed-bitcode option.
1064   if (Arg *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
1065     StringRef Name = A->getValue();
1066     unsigned Model = llvm::StringSwitch<unsigned>(Name)
1067         .Case("off", CodeGenOptions::Embed_Off)
1068         .Case("all", CodeGenOptions::Embed_All)
1069         .Case("bitcode", CodeGenOptions::Embed_Bitcode)
1070         .Case("marker", CodeGenOptions::Embed_Marker)
1071         .Default(~0U);
1072     if (Model == ~0U) {
1073       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1074       Success = false;
1075     } else
1076       Opts.setEmbedBitcode(
1077           static_cast<CodeGenOptions::EmbedBitcodeKind>(Model));
1078   }
1079   // FIXME: For backend options that are not yet recorded as function
1080   // attributes in the IR, keep track of them so we can embed them in a
1081   // separate data section and use them when building the bitcode.
1082   if (Opts.getEmbedBitcode() == CodeGenOptions::Embed_All) {
1083     for (const auto &A : Args) {
1084       // Do not encode output and input.
1085       if (A->getOption().getID() == options::OPT_o ||
1086           A->getOption().getID() == options::OPT_INPUT ||
1087           A->getOption().getID() == options::OPT_x ||
1088           A->getOption().getID() == options::OPT_fembed_bitcode ||
1089           A->getOption().matches(options::OPT_W_Group))
1090         continue;
1091       ArgStringList ASL;
1092       A->render(Args, ASL);
1093       for (const auto &arg : ASL) {
1094         StringRef ArgStr(arg);
1095         Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1096         // using \00 to separate each commandline options.
1097         Opts.CmdArgs.push_back('\0');
1098       }
1099     }
1100   }
1101 
1102   Opts.PreserveVec3Type = Args.hasArg(OPT_fpreserve_vec3_type);
1103   Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
1104   Opts.InstrumentFunctionsAfterInlining =
1105       Args.hasArg(OPT_finstrument_functions_after_inlining);
1106   Opts.InstrumentFunctionEntryBare =
1107       Args.hasArg(OPT_finstrument_function_entry_bare);
1108 
1109   Opts.XRayInstrumentFunctions =
1110       Args.hasArg(OPT_fxray_instrument);
1111   Opts.XRayAlwaysEmitCustomEvents =
1112       Args.hasArg(OPT_fxray_always_emit_customevents);
1113   Opts.XRayAlwaysEmitTypedEvents =
1114       Args.hasArg(OPT_fxray_always_emit_typedevents);
1115   Opts.XRayInstructionThreshold =
1116       getLastArgIntValue(Args, OPT_fxray_instruction_threshold_EQ, 200, Diags);
1117   Opts.XRayIgnoreLoops = Args.hasArg(OPT_fxray_ignore_loops);
1118   Opts.XRayOmitFunctionIndex = Args.hasArg(OPT_fno_xray_function_index);
1119 
1120   auto XRayInstrBundles =
1121       Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1122   if (XRayInstrBundles.empty())
1123     Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
1124   else
1125     for (const auto &A : XRayInstrBundles)
1126       parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1127                                      Diags, Opts.XRayInstrumentationBundle);
1128 
1129   Opts.PatchableFunctionEntryCount =
1130       getLastArgIntValue(Args, OPT_fpatchable_function_entry_EQ, 0, Diags);
1131   Opts.PatchableFunctionEntryOffset = getLastArgIntValue(
1132       Args, OPT_fpatchable_function_entry_offset_EQ, 0, Diags);
1133   Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
1134   Opts.CallFEntry = Args.hasArg(OPT_mfentry);
1135   Opts.MNopMCount = Args.hasArg(OPT_mnop_mcount);
1136   Opts.RecordMCount = Args.hasArg(OPT_mrecord_mcount);
1137   Opts.PackedStack = Args.hasArg(OPT_mpacked_stack);
1138   Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
1139 
1140   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1141     StringRef Name = A->getValue();
1142     if (Name == "full") {
1143       Opts.CFProtectionReturn = 1;
1144       Opts.CFProtectionBranch = 1;
1145     } else if (Name == "return")
1146       Opts.CFProtectionReturn = 1;
1147     else if (Name == "branch")
1148       Opts.CFProtectionBranch = 1;
1149     else if (Name != "none") {
1150       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1151       Success = false;
1152     }
1153   }
1154 
1155   if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
1156                                      OPT_compress_debug_sections_EQ)) {
1157     if (A->getOption().getID() == OPT_compress_debug_sections) {
1158       // TODO: be more clever about the compression type auto-detection
1159       Opts.setCompressDebugSections(llvm::DebugCompressionType::GNU);
1160     } else {
1161       auto DCT = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
1162                      .Case("none", llvm::DebugCompressionType::None)
1163                      .Case("zlib", llvm::DebugCompressionType::Z)
1164                      .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
1165                      .Default(llvm::DebugCompressionType::None);
1166       Opts.setCompressDebugSections(DCT);
1167     }
1168   }
1169 
1170   Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
1171   Opts.DebugCompilationDir =
1172       std::string(Args.getLastArgValue(OPT_fdebug_compilation_dir));
1173   for (auto *A :
1174        Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1175     CodeGenOptions::BitcodeFileToLink F;
1176     F.Filename = A->getValue();
1177     if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1178       F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
1179       // When linking CUDA bitcode, propagate function attributes so that
1180       // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1181       F.PropagateAttrs = true;
1182       F.Internalize = true;
1183     }
1184     Opts.LinkBitcodeFiles.push_back(F);
1185   }
1186   Opts.SanitizeCoverageType =
1187       getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags);
1188   Opts.SanitizeCoverageIndirectCalls =
1189       Args.hasArg(OPT_fsanitize_coverage_indirect_calls);
1190   Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb);
1191   Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp);
1192   Opts.SanitizeCoverageTraceDiv = Args.hasArg(OPT_fsanitize_coverage_trace_div);
1193   Opts.SanitizeCoverageTraceGep = Args.hasArg(OPT_fsanitize_coverage_trace_gep);
1194   Opts.SanitizeCoverage8bitCounters =
1195       Args.hasArg(OPT_fsanitize_coverage_8bit_counters);
1196   Opts.SanitizeCoverageTracePC = Args.hasArg(OPT_fsanitize_coverage_trace_pc);
1197   Opts.SanitizeCoverageTracePCGuard =
1198       Args.hasArg(OPT_fsanitize_coverage_trace_pc_guard);
1199   Opts.SanitizeCoverageNoPrune = Args.hasArg(OPT_fsanitize_coverage_no_prune);
1200   Opts.SanitizeCoverageInline8bitCounters =
1201       Args.hasArg(OPT_fsanitize_coverage_inline_8bit_counters);
1202   Opts.SanitizeCoverageInlineBoolFlag =
1203       Args.hasArg(OPT_fsanitize_coverage_inline_bool_flag);
1204   Opts.SanitizeCoveragePCTable = Args.hasArg(OPT_fsanitize_coverage_pc_table);
1205   Opts.SanitizeCoverageStackDepth =
1206       Args.hasArg(OPT_fsanitize_coverage_stack_depth);
1207   Opts.SanitizeCoverageAllowlistFiles =
1208       Args.getAllArgValues(OPT_fsanitize_coverage_allowlist);
1209   Opts.SanitizeCoverageBlocklistFiles =
1210       Args.getAllArgValues(OPT_fsanitize_coverage_blocklist);
1211   Opts.SanitizeMemoryTrackOrigins =
1212       getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags);
1213   Opts.SanitizeMemoryUseAfterDtor =
1214       Args.hasFlag(OPT_fsanitize_memory_use_after_dtor,
1215                    OPT_fno_sanitize_memory_use_after_dtor,
1216                    false);
1217   Opts.SanitizeMinimalRuntime = Args.hasArg(OPT_fsanitize_minimal_runtime);
1218   Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso);
1219   Opts.SanitizeCfiICallGeneralizePointers =
1220       Args.hasArg(OPT_fsanitize_cfi_icall_generalize_pointers);
1221   Opts.SanitizeCfiCanonicalJumpTables =
1222       Args.hasArg(OPT_fsanitize_cfi_canonical_jump_tables);
1223   Opts.SanitizeStats = Args.hasArg(OPT_fsanitize_stats);
1224   if (Arg *A = Args.getLastArg(
1225           OPT_fsanitize_address_poison_custom_array_cookie,
1226           OPT_fno_sanitize_address_poison_custom_array_cookie)) {
1227     Opts.SanitizeAddressPoisonCustomArrayCookie =
1228         A->getOption().getID() ==
1229         OPT_fsanitize_address_poison_custom_array_cookie;
1230   }
1231   if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_after_scope,
1232                                OPT_fno_sanitize_address_use_after_scope)) {
1233     Opts.SanitizeAddressUseAfterScope =
1234         A->getOption().getID() == OPT_fsanitize_address_use_after_scope;
1235   }
1236   Opts.SanitizeAddressGlobalsDeadStripping =
1237       Args.hasArg(OPT_fsanitize_address_globals_dead_stripping);
1238   if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_odr_indicator,
1239                                OPT_fno_sanitize_address_use_odr_indicator)) {
1240     Opts.SanitizeAddressUseOdrIndicator =
1241         A->getOption().getID() == OPT_fsanitize_address_use_odr_indicator;
1242   }
1243   Opts.SSPBufferSize =
1244       getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
1245   Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
1246   if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
1247     StringRef Val = A->getValue();
1248     unsigned StackAlignment = Opts.StackAlignment;
1249     Val.getAsInteger(10, StackAlignment);
1250     Opts.StackAlignment = StackAlignment;
1251   }
1252 
1253   if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) {
1254     StringRef Val = A->getValue();
1255     unsigned StackProbeSize = Opts.StackProbeSize;
1256     Val.getAsInteger(0, StackProbeSize);
1257     Opts.StackProbeSize = StackProbeSize;
1258   }
1259 
1260   Opts.NoStackArgProbe = Args.hasArg(OPT_mno_stack_arg_probe);
1261 
1262   Opts.StackClashProtector = Args.hasArg(OPT_fstack_clash_protection);
1263 
1264   if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
1265     StringRef Name = A->getValue();
1266     unsigned Method = llvm::StringSwitch<unsigned>(Name)
1267       .Case("legacy", CodeGenOptions::Legacy)
1268       .Case("non-legacy", CodeGenOptions::NonLegacy)
1269       .Case("mixed", CodeGenOptions::Mixed)
1270       .Default(~0U);
1271     if (Method == ~0U) {
1272       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1273       Success = false;
1274     } else {
1275       Opts.setObjCDispatchMethod(
1276         static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
1277     }
1278   }
1279 
1280 
1281   if (Args.hasArg(OPT_fno_objc_convert_messages_to_runtime_calls))
1282     Opts.ObjCConvertMessagesToRuntimeCalls = 0;
1283 
1284   if (Args.getLastArg(OPT_femulated_tls) ||
1285       Args.getLastArg(OPT_fno_emulated_tls)) {
1286     Opts.ExplicitEmulatedTLS = true;
1287     Opts.EmulatedTLS =
1288         Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false);
1289   }
1290 
1291   if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
1292     StringRef Name = A->getValue();
1293     unsigned Model = llvm::StringSwitch<unsigned>(Name)
1294         .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
1295         .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
1296         .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
1297         .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
1298         .Default(~0U);
1299     if (Model == ~0U) {
1300       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1301       Success = false;
1302     } else {
1303       Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
1304     }
1305   }
1306 
1307   Opts.TLSSize = getLastArgIntValue(Args, OPT_mtls_size_EQ, 0, Diags);
1308 
1309   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1310     StringRef Val = A->getValue();
1311     Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
1312     if (!Opts.FPDenormalMode.isValid())
1313       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1314   }
1315 
1316   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
1317     StringRef Val = A->getValue();
1318     Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
1319     if (!Opts.FP32DenormalMode.isValid())
1320       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1321   }
1322 
1323   // X86_32 has -fppc-struct-return and -freg-struct-return.
1324   // PPC32 has -maix-struct-return and -msvr4-struct-return.
1325   if (Arg *A =
1326           Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
1327                           OPT_maix_struct_return, OPT_msvr4_struct_return)) {
1328     // TODO: We might want to consider enabling these options on AIX in the
1329     // future.
1330     if (T.isOSAIX())
1331       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1332           << A->getSpelling() << T.str();
1333 
1334     const Option &O = A->getOption();
1335     if (O.matches(OPT_fpcc_struct_return) ||
1336         O.matches(OPT_maix_struct_return)) {
1337       Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1338     } else {
1339       assert(O.matches(OPT_freg_struct_return) ||
1340              O.matches(OPT_msvr4_struct_return));
1341       Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1342     }
1343   }
1344 
1345   Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
1346   Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option);
1347   bool NeedLocTracking = false;
1348 
1349   Opts.OptRecordFile = std::string(Args.getLastArgValue(OPT_opt_record_file));
1350   if (!Opts.OptRecordFile.empty())
1351     NeedLocTracking = true;
1352 
1353   if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
1354     Opts.OptRecordPasses = A->getValue();
1355     NeedLocTracking = true;
1356   }
1357 
1358   if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
1359     Opts.OptRecordFormat = A->getValue();
1360     NeedLocTracking = true;
1361   }
1362 
1363   if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
1364     Opts.OptimizationRemarkPattern =
1365         GenerateOptimizationRemarkRegex(Diags, Args, A);
1366     NeedLocTracking = true;
1367   }
1368 
1369   if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
1370     Opts.OptimizationRemarkMissedPattern =
1371         GenerateOptimizationRemarkRegex(Diags, Args, A);
1372     NeedLocTracking = true;
1373   }
1374 
1375   if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
1376     Opts.OptimizationRemarkAnalysisPattern =
1377         GenerateOptimizationRemarkRegex(Diags, Args, A);
1378     NeedLocTracking = true;
1379   }
1380 
1381   Opts.DiagnosticsWithHotness =
1382       Args.hasArg(options::OPT_fdiagnostics_show_hotness);
1383   bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
1384   bool UsingProfile = UsingSampleProfile ||
1385       (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
1386 
1387   if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1388       // An IR file will contain PGO as metadata
1389       IK.getLanguage() != Language::LLVM_IR)
1390     Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1391         << "-fdiagnostics-show-hotness";
1392 
1393   Opts.DiagnosticsHotnessThreshold = getLastArgUInt64Value(
1394       Args, options::OPT_fdiagnostics_hotness_threshold_EQ, 0);
1395   if (Opts.DiagnosticsHotnessThreshold > 0 && !UsingProfile)
1396     Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1397         << "-fdiagnostics-hotness-threshold=";
1398 
1399   // If the user requested to use a sample profile for PGO, then the
1400   // backend will need to track source location information so the profile
1401   // can be incorporated into the IR.
1402   if (UsingSampleProfile)
1403     NeedLocTracking = true;
1404 
1405   // If the user requested a flag that requires source locations available in
1406   // the backend, make sure that the backend tracks source location information.
1407   if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
1408     Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
1409 
1410   Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
1411 
1412   // Parse -fsanitize-recover= arguments.
1413   // FIXME: Report unrecoverable sanitizers incorrectly specified here.
1414   parseSanitizerKinds("-fsanitize-recover=",
1415                       Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
1416                       Opts.SanitizeRecover);
1417   parseSanitizerKinds("-fsanitize-trap=",
1418                       Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
1419                       Opts.SanitizeTrap);
1420 
1421   Opts.CudaGpuBinaryFileName =
1422       std::string(Args.getLastArgValue(OPT_fcuda_include_gpubinary));
1423 
1424   Opts.Backchain = Args.hasArg(OPT_mbackchain);
1425 
1426   Opts.EmitCheckPathComponentsToStrip = getLastArgIntValue(
1427       Args, OPT_fsanitize_undefined_strip_path_components_EQ, 0, Diags);
1428 
1429   Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
1430 
1431   Opts.Addrsig = Args.hasArg(OPT_faddrsig);
1432 
1433   Opts.KeepStaticConsts = Args.hasArg(OPT_fkeep_static_consts);
1434 
1435   Opts.SpeculativeLoadHardening = Args.hasArg(OPT_mspeculative_load_hardening);
1436 
1437   Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
1438 
1439   Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
1440 
1441   Opts.SymbolPartition =
1442       std::string(Args.getLastArgValue(OPT_fsymbol_partition_EQ));
1443 
1444   Opts.ForceAAPCSBitfieldLoad = Args.hasArg(OPT_ForceAAPCSBitfieldLoad);
1445   return Success;
1446 }
1447 
1448 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
1449                                       ArgList &Args) {
1450   Opts.OutputFile = std::string(Args.getLastArgValue(OPT_dependency_file));
1451   Opts.Targets = Args.getAllArgValues(OPT_MT);
1452   Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
1453   Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
1454   Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
1455   Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
1456   Opts.HeaderIncludeOutputFile =
1457       std::string(Args.getLastArgValue(OPT_header_include_file));
1458   Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
1459   if (Args.hasArg(OPT_show_includes)) {
1460     // Writing both /showIncludes and preprocessor output to stdout
1461     // would produce interleaved output, so use stderr for /showIncludes.
1462     // This behaves the same as cl.exe, when /E, /EP or /P are passed.
1463     if (Args.hasArg(options::OPT_E) || Args.hasArg(options::OPT_P))
1464       Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
1465     else
1466       Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
1467   } else {
1468     Opts.ShowIncludesDest = ShowIncludesDestination::None;
1469   }
1470   Opts.DOTOutputFile = std::string(Args.getLastArgValue(OPT_dependency_dot));
1471   Opts.ModuleDependencyOutputDir =
1472       std::string(Args.getLastArgValue(OPT_module_dependency_dir));
1473   if (Args.hasArg(OPT_MV))
1474     Opts.OutputFormat = DependencyOutputFormat::NMake;
1475   // Add sanitizer blacklists as extra dependencies.
1476   // They won't be discovered by the regular preprocessor, so
1477   // we let make / ninja to know about this implicit dependency.
1478   if (!Args.hasArg(OPT_fno_sanitize_blacklist)) {
1479     for (const auto *A : Args.filtered(OPT_fsanitize_blacklist)) {
1480       StringRef Val = A->getValue();
1481       if (Val.find('=') == StringRef::npos)
1482         Opts.ExtraDeps.push_back(std::string(Val));
1483     }
1484     if (Opts.IncludeSystemHeaders) {
1485       for (const auto *A : Args.filtered(OPT_fsanitize_system_blacklist)) {
1486         StringRef Val = A->getValue();
1487         if (Val.find('=') == StringRef::npos)
1488           Opts.ExtraDeps.push_back(std::string(Val));
1489       }
1490     }
1491   }
1492 
1493   // Propagate the extra dependencies.
1494   for (const auto *A : Args.filtered(OPT_fdepfile_entry)) {
1495     Opts.ExtraDeps.push_back(A->getValue());
1496   }
1497 
1498   // Only the -fmodule-file=<file> form.
1499   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1500     StringRef Val = A->getValue();
1501     if (Val.find('=') == StringRef::npos)
1502       Opts.ExtraDeps.push_back(std::string(Val));
1503   }
1504 }
1505 
1506 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
1507   // Color diagnostics default to auto ("on" if terminal supports) in the driver
1508   // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
1509   // Support both clang's -f[no-]color-diagnostics and gcc's
1510   // -f[no-]diagnostics-colors[=never|always|auto].
1511   enum {
1512     Colors_On,
1513     Colors_Off,
1514     Colors_Auto
1515   } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
1516   for (auto *A : Args) {
1517     const Option &O = A->getOption();
1518     if (O.matches(options::OPT_fcolor_diagnostics) ||
1519         O.matches(options::OPT_fdiagnostics_color)) {
1520       ShowColors = Colors_On;
1521     } else if (O.matches(options::OPT_fno_color_diagnostics) ||
1522                O.matches(options::OPT_fno_diagnostics_color)) {
1523       ShowColors = Colors_Off;
1524     } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
1525       StringRef Value(A->getValue());
1526       if (Value == "always")
1527         ShowColors = Colors_On;
1528       else if (Value == "never")
1529         ShowColors = Colors_Off;
1530       else if (Value == "auto")
1531         ShowColors = Colors_Auto;
1532     }
1533   }
1534   return ShowColors == Colors_On ||
1535          (ShowColors == Colors_Auto &&
1536           llvm::sys::Process::StandardErrHasColors());
1537 }
1538 
1539 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
1540                                 DiagnosticsEngine *Diags) {
1541   bool Success = true;
1542   for (const auto &Prefix : VerifyPrefixes) {
1543     // Every prefix must start with a letter and contain only alphanumeric
1544     // characters, hyphens, and underscores.
1545     auto BadChar = llvm::find_if(Prefix, [](char C) {
1546       return !isAlphanumeric(C) && C != '-' && C != '_';
1547     });
1548     if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
1549       Success = false;
1550       if (Diags) {
1551         Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
1552         Diags->Report(diag::note_drv_verify_prefix_spelling);
1553       }
1554     }
1555   }
1556   return Success;
1557 }
1558 
1559 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
1560                                 DiagnosticsEngine *Diags,
1561                                 bool DefaultDiagColor) {
1562   bool Success = true;
1563 
1564   Opts.DiagnosticLogFile =
1565       std::string(Args.getLastArgValue(OPT_diagnostic_log_file));
1566   if (Arg *A =
1567           Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
1568     Opts.DiagnosticSerializationFile = A->getValue();
1569   Opts.IgnoreWarnings = Args.hasArg(OPT_w);
1570   Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
1571   Opts.Pedantic = Args.hasArg(OPT_pedantic);
1572   Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
1573   Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
1574   Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
1575   Opts.ShowColumn = !Args.hasArg(OPT_fno_show_column);
1576   Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
1577   Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
1578   Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths);
1579   Opts.ShowOptionNames = !Args.hasArg(OPT_fno_diagnostics_show_option);
1580 
1581   // Default behavior is to not to show note include stacks.
1582   Opts.ShowNoteIncludeStack = false;
1583   if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
1584                                OPT_fno_diagnostics_show_note_include_stack))
1585     if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
1586       Opts.ShowNoteIncludeStack = true;
1587 
1588   StringRef ShowOverloads =
1589     Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
1590   if (ShowOverloads == "best")
1591     Opts.setShowOverloads(Ovl_Best);
1592   else if (ShowOverloads == "all")
1593     Opts.setShowOverloads(Ovl_All);
1594   else {
1595     Success = false;
1596     if (Diags)
1597       Diags->Report(diag::err_drv_invalid_value)
1598       << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
1599       << ShowOverloads;
1600   }
1601 
1602   StringRef ShowCategory =
1603     Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
1604   if (ShowCategory == "none")
1605     Opts.ShowCategories = 0;
1606   else if (ShowCategory == "id")
1607     Opts.ShowCategories = 1;
1608   else if (ShowCategory == "name")
1609     Opts.ShowCategories = 2;
1610   else {
1611     Success = false;
1612     if (Diags)
1613       Diags->Report(diag::err_drv_invalid_value)
1614       << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
1615       << ShowCategory;
1616   }
1617 
1618   StringRef Format =
1619     Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
1620   if (Format == "clang")
1621     Opts.setFormat(DiagnosticOptions::Clang);
1622   else if (Format == "msvc")
1623     Opts.setFormat(DiagnosticOptions::MSVC);
1624   else if (Format == "msvc-fallback") {
1625     Opts.setFormat(DiagnosticOptions::MSVC);
1626     Opts.CLFallbackMode = true;
1627   } else if (Format == "vi")
1628     Opts.setFormat(DiagnosticOptions::Vi);
1629   else {
1630     Success = false;
1631     if (Diags)
1632       Diags->Report(diag::err_drv_invalid_value)
1633       << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
1634       << Format;
1635   }
1636 
1637   Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
1638   Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
1639   Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
1640   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
1641   Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
1642   if (Args.hasArg(OPT_verify))
1643     Opts.VerifyPrefixes.push_back("expected");
1644   // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
1645   // then sort it to prepare for fast lookup using std::binary_search.
1646   if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) {
1647     Opts.VerifyDiagnostics = false;
1648     Success = false;
1649   }
1650   else
1651     llvm::sort(Opts.VerifyPrefixes);
1652   DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
1653   Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
1654     Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
1655     Diags, DiagMask);
1656   if (Args.hasArg(OPT_verify_ignore_unexpected))
1657     DiagMask = DiagnosticLevelMask::All;
1658   Opts.setVerifyIgnoreUnexpected(DiagMask);
1659   Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
1660   Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
1661   Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
1662   Opts.MacroBacktraceLimit =
1663       getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
1664                          DiagnosticOptions::DefaultMacroBacktraceLimit, Diags);
1665   Opts.TemplateBacktraceLimit = getLastArgIntValue(
1666       Args, OPT_ftemplate_backtrace_limit,
1667       DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags);
1668   Opts.ConstexprBacktraceLimit = getLastArgIntValue(
1669       Args, OPT_fconstexpr_backtrace_limit,
1670       DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags);
1671   Opts.SpellCheckingLimit = getLastArgIntValue(
1672       Args, OPT_fspell_checking_limit,
1673       DiagnosticOptions::DefaultSpellCheckingLimit, Diags);
1674   Opts.SnippetLineLimit = getLastArgIntValue(
1675       Args, OPT_fcaret_diagnostics_max_lines,
1676       DiagnosticOptions::DefaultSnippetLineLimit, Diags);
1677   Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
1678                                     DiagnosticOptions::DefaultTabStop, Diags);
1679   if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
1680     Opts.TabStop = DiagnosticOptions::DefaultTabStop;
1681     if (Diags)
1682       Diags->Report(diag::warn_ignoring_ftabstop_value)
1683       << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
1684   }
1685   Opts.MessageLength =
1686       getLastArgIntValue(Args, OPT_fmessage_length_EQ, 0, Diags);
1687 
1688   Opts.UndefPrefixes = Args.getAllArgValues(OPT_Wundef_prefix_EQ);
1689 
1690   addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
1691   addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
1692 
1693   return Success;
1694 }
1695 
1696 static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
1697   Opts.WorkingDir = std::string(Args.getLastArgValue(OPT_working_directory));
1698 }
1699 
1700 /// Parse the argument to the -ftest-module-file-extension
1701 /// command-line argument.
1702 ///
1703 /// \returns true on error, false on success.
1704 static bool parseTestModuleFileExtensionArg(StringRef Arg,
1705                                             std::string &BlockName,
1706                                             unsigned &MajorVersion,
1707                                             unsigned &MinorVersion,
1708                                             bool &Hashed,
1709                                             std::string &UserInfo) {
1710   SmallVector<StringRef, 5> Args;
1711   Arg.split(Args, ':', 5);
1712   if (Args.size() < 5)
1713     return true;
1714 
1715   BlockName = std::string(Args[0]);
1716   if (Args[1].getAsInteger(10, MajorVersion)) return true;
1717   if (Args[2].getAsInteger(10, MinorVersion)) return true;
1718   if (Args[3].getAsInteger(2, Hashed)) return true;
1719   if (Args.size() > 4)
1720     UserInfo = std::string(Args[4]);
1721   return false;
1722 }
1723 
1724 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
1725                                    DiagnosticsEngine &Diags,
1726                                    bool &IsHeaderFile) {
1727   Opts.ProgramAction = frontend::ParseSyntaxOnly;
1728   if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
1729     switch (A->getOption().getID()) {
1730     default:
1731       llvm_unreachable("Invalid option in group!");
1732     case OPT_ast_list:
1733       Opts.ProgramAction = frontend::ASTDeclList; break;
1734     case OPT_ast_dump_all_EQ:
1735     case OPT_ast_dump_EQ: {
1736       unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
1737                          .CaseLower("default", ADOF_Default)
1738                          .CaseLower("json", ADOF_JSON)
1739                          .Default(std::numeric_limits<unsigned>::max());
1740 
1741       if (Val != std::numeric_limits<unsigned>::max())
1742         Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
1743       else {
1744         Diags.Report(diag::err_drv_invalid_value)
1745             << A->getAsString(Args) << A->getValue();
1746         Opts.ASTDumpFormat = ADOF_Default;
1747       }
1748       LLVM_FALLTHROUGH;
1749     }
1750     case OPT_ast_dump:
1751     case OPT_ast_dump_all:
1752     case OPT_ast_dump_lookups:
1753     case OPT_ast_dump_decl_types:
1754       Opts.ProgramAction = frontend::ASTDump; break;
1755     case OPT_ast_print:
1756       Opts.ProgramAction = frontend::ASTPrint; break;
1757     case OPT_ast_view:
1758       Opts.ProgramAction = frontend::ASTView; break;
1759     case OPT_compiler_options_dump:
1760       Opts.ProgramAction = frontend::DumpCompilerOptions; break;
1761     case OPT_dump_raw_tokens:
1762       Opts.ProgramAction = frontend::DumpRawTokens; break;
1763     case OPT_dump_tokens:
1764       Opts.ProgramAction = frontend::DumpTokens; break;
1765     case OPT_S:
1766       Opts.ProgramAction = frontend::EmitAssembly; break;
1767     case OPT_emit_llvm_bc:
1768       Opts.ProgramAction = frontend::EmitBC; break;
1769     case OPT_emit_html:
1770       Opts.ProgramAction = frontend::EmitHTML; break;
1771     case OPT_emit_llvm:
1772       Opts.ProgramAction = frontend::EmitLLVM; break;
1773     case OPT_emit_llvm_only:
1774       Opts.ProgramAction = frontend::EmitLLVMOnly; break;
1775     case OPT_emit_codegen_only:
1776       Opts.ProgramAction = frontend::EmitCodeGenOnly; break;
1777     case OPT_emit_obj:
1778       Opts.ProgramAction = frontend::EmitObj; break;
1779     case OPT_fixit_EQ:
1780       Opts.FixItSuffix = A->getValue();
1781       LLVM_FALLTHROUGH;
1782     case OPT_fixit:
1783       Opts.ProgramAction = frontend::FixIt; break;
1784     case OPT_emit_module:
1785       Opts.ProgramAction = frontend::GenerateModule; break;
1786     case OPT_emit_module_interface:
1787       Opts.ProgramAction = frontend::GenerateModuleInterface; break;
1788     case OPT_emit_header_module:
1789       Opts.ProgramAction = frontend::GenerateHeaderModule; break;
1790     case OPT_emit_pch:
1791       Opts.ProgramAction = frontend::GeneratePCH; break;
1792     case OPT_emit_interface_stubs: {
1793       StringRef ArgStr =
1794           Args.hasArg(OPT_interface_stub_version_EQ)
1795               ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
1796               : "experimental-ifs-v2";
1797       if (ArgStr == "experimental-yaml-elf-v1" ||
1798           ArgStr == "experimental-ifs-v1" ||
1799           ArgStr == "experimental-tapi-elf-v1") {
1800         std::string ErrorMessage =
1801             "Invalid interface stub format: " + ArgStr.str() +
1802             " is deprecated.";
1803         Diags.Report(diag::err_drv_invalid_value)
1804             << "Must specify a valid interface stub format type, ie: "
1805                "-interface-stub-version=experimental-ifs-v2"
1806             << ErrorMessage;
1807       } else if (!ArgStr.startswith("experimental-ifs-")) {
1808         std::string ErrorMessage =
1809             "Invalid interface stub format: " + ArgStr.str() + ".";
1810         Diags.Report(diag::err_drv_invalid_value)
1811             << "Must specify a valid interface stub format type, ie: "
1812                "-interface-stub-version=experimental-ifs-v2"
1813             << ErrorMessage;
1814       } else {
1815         Opts.ProgramAction = frontend::GenerateInterfaceStubs;
1816       }
1817       break;
1818     }
1819     case OPT_init_only:
1820       Opts.ProgramAction = frontend::InitOnly; break;
1821     case OPT_fsyntax_only:
1822       Opts.ProgramAction = frontend::ParseSyntaxOnly; break;
1823     case OPT_module_file_info:
1824       Opts.ProgramAction = frontend::ModuleFileInfo; break;
1825     case OPT_verify_pch:
1826       Opts.ProgramAction = frontend::VerifyPCH; break;
1827     case OPT_print_preamble:
1828       Opts.ProgramAction = frontend::PrintPreamble; break;
1829     case OPT_E:
1830       Opts.ProgramAction = frontend::PrintPreprocessedInput; break;
1831     case OPT_templight_dump:
1832       Opts.ProgramAction = frontend::TemplightDump; break;
1833     case OPT_rewrite_macros:
1834       Opts.ProgramAction = frontend::RewriteMacros; break;
1835     case OPT_rewrite_objc:
1836       Opts.ProgramAction = frontend::RewriteObjC; break;
1837     case OPT_rewrite_test:
1838       Opts.ProgramAction = frontend::RewriteTest; break;
1839     case OPT_analyze:
1840       Opts.ProgramAction = frontend::RunAnalysis; break;
1841     case OPT_migrate:
1842       Opts.ProgramAction = frontend::MigrateSource; break;
1843     case OPT_Eonly:
1844       Opts.ProgramAction = frontend::RunPreprocessorOnly; break;
1845     case OPT_print_dependency_directives_minimized_source:
1846       Opts.ProgramAction =
1847           frontend::PrintDependencyDirectivesSourceMinimizerOutput;
1848       break;
1849     }
1850   }
1851 
1852   if (const Arg* A = Args.getLastArg(OPT_plugin)) {
1853     Opts.Plugins.emplace_back(A->getValue(0));
1854     Opts.ProgramAction = frontend::PluginAction;
1855     Opts.ActionName = A->getValue();
1856   }
1857   Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
1858   for (const auto *AA : Args.filtered(OPT_plugin_arg))
1859     Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
1860 
1861   for (const std::string &Arg :
1862          Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
1863     std::string BlockName;
1864     unsigned MajorVersion;
1865     unsigned MinorVersion;
1866     bool Hashed;
1867     std::string UserInfo;
1868     if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
1869                                         MinorVersion, Hashed, UserInfo)) {
1870       Diags.Report(diag::err_test_module_file_extension_format) << Arg;
1871 
1872       continue;
1873     }
1874 
1875     // Add the testing module file extension.
1876     Opts.ModuleFileExtensions.push_back(
1877         std::make_shared<TestModuleFileExtension>(
1878             BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
1879   }
1880 
1881   if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1882     Opts.CodeCompletionAt =
1883       ParsedSourceLocation::FromString(A->getValue());
1884     if (Opts.CodeCompletionAt.FileName.empty())
1885       Diags.Report(diag::err_drv_invalid_value)
1886         << A->getAsString(Args) << A->getValue();
1887   }
1888   Opts.DisableFree = Args.hasArg(OPT_disable_free);
1889 
1890   Opts.OutputFile = std::string(Args.getLastArgValue(OPT_o));
1891   Opts.Plugins = Args.getAllArgValues(OPT_load);
1892   Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
1893   Opts.ShowHelp = Args.hasArg(OPT_help);
1894   Opts.ShowStats = Args.hasArg(OPT_print_stats);
1895   Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
1896   Opts.PrintSupportedCPUs = Args.hasArg(OPT_print_supported_cpus);
1897   Opts.TimeTrace = Args.hasArg(OPT_ftime_trace);
1898   Opts.TimeTraceGranularity = getLastArgIntValue(
1899       Args, OPT_ftime_trace_granularity_EQ, Opts.TimeTraceGranularity, Diags);
1900   Opts.ShowVersion = Args.hasArg(OPT_version);
1901   Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
1902   Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
1903   Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
1904   Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
1905   Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
1906   Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
1907   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
1908   Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
1909   Opts.ASTDumpFilter = std::string(Args.getLastArgValue(OPT_ast_dump_filter));
1910   Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
1911   Opts.ASTDumpDeclTypes = Args.hasArg(OPT_ast_dump_decl_types);
1912   Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
1913   Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex;
1914   Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
1915   // Only the -fmodule-file=<file> form.
1916   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1917     StringRef Val = A->getValue();
1918     if (Val.find('=') == StringRef::npos)
1919       Opts.ModuleFiles.push_back(std::string(Val));
1920   }
1921   Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
1922   Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files);
1923   Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp);
1924   Opts.UseTemporary = !Args.hasArg(OPT_fno_temp_file);
1925   Opts.IsSystemModule = Args.hasArg(OPT_fsystem_module);
1926 
1927   if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
1928     Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
1929                                                            << "-emit-module";
1930 
1931   Opts.CodeCompleteOpts.IncludeMacros
1932     = Args.hasArg(OPT_code_completion_macros);
1933   Opts.CodeCompleteOpts.IncludeCodePatterns
1934     = Args.hasArg(OPT_code_completion_patterns);
1935   Opts.CodeCompleteOpts.IncludeGlobals
1936     = !Args.hasArg(OPT_no_code_completion_globals);
1937   Opts.CodeCompleteOpts.IncludeNamespaceLevelDecls
1938     = !Args.hasArg(OPT_no_code_completion_ns_level_decls);
1939   Opts.CodeCompleteOpts.IncludeBriefComments
1940     = Args.hasArg(OPT_code_completion_brief_comments);
1941   Opts.CodeCompleteOpts.IncludeFixIts
1942     = Args.hasArg(OPT_code_completion_with_fixits);
1943 
1944   Opts.OverrideRecordLayoutsFile =
1945       std::string(Args.getLastArgValue(OPT_foverride_record_layout_EQ));
1946   Opts.AuxTriple = std::string(Args.getLastArgValue(OPT_aux_triple));
1947   if (Args.hasArg(OPT_aux_target_cpu))
1948     Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
1949   if (Args.hasArg(OPT_aux_target_feature))
1950     Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
1951   Opts.StatsFile = std::string(Args.getLastArgValue(OPT_stats_file));
1952 
1953   if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
1954                                      OPT_arcmt_modify,
1955                                      OPT_arcmt_migrate)) {
1956     switch (A->getOption().getID()) {
1957     default:
1958       llvm_unreachable("missed a case");
1959     case OPT_arcmt_check:
1960       Opts.ARCMTAction = FrontendOptions::ARCMT_Check;
1961       break;
1962     case OPT_arcmt_modify:
1963       Opts.ARCMTAction = FrontendOptions::ARCMT_Modify;
1964       break;
1965     case OPT_arcmt_migrate:
1966       Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate;
1967       break;
1968     }
1969   }
1970   Opts.MTMigrateDir =
1971       std::string(Args.getLastArgValue(OPT_mt_migrate_directory));
1972   Opts.ARCMTMigrateReportOut =
1973       std::string(Args.getLastArgValue(OPT_arcmt_migrate_report_output));
1974   Opts.ARCMTMigrateEmitARCErrors
1975     = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
1976 
1977   if (Args.hasArg(OPT_objcmt_migrate_literals))
1978     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals;
1979   if (Args.hasArg(OPT_objcmt_migrate_subscripting))
1980     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting;
1981   if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
1982     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_PropertyDotSyntax;
1983   if (Args.hasArg(OPT_objcmt_migrate_property))
1984     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Property;
1985   if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
1986     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadonlyProperty;
1987   if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
1988     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadwriteProperty;
1989   if (Args.hasArg(OPT_objcmt_migrate_annotation))
1990     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Annotation;
1991   if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
1992     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReturnsInnerPointerProperty;
1993   if (Args.hasArg(OPT_objcmt_migrate_instancetype))
1994     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Instancetype;
1995   if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
1996     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsMacros;
1997   if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
1998     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ProtocolConformance;
1999   if (Args.hasArg(OPT_objcmt_atomic_property))
2000     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_AtomicProperty;
2001   if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
2002     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty;
2003   if (Args.hasArg(OPT_objcmt_migrate_designated_init))
2004     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_DesignatedInitializer;
2005   if (Args.hasArg(OPT_objcmt_migrate_all))
2006     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_MigrateDecls;
2007 
2008   Opts.ObjCMTWhiteListPath =
2009       std::string(Args.getLastArgValue(OPT_objcmt_whitelist_dir_path));
2010 
2011   if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
2012       Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
2013     Diags.Report(diag::err_drv_argument_not_allowed_with)
2014       << "ARC migration" << "ObjC migration";
2015   }
2016 
2017   InputKind DashX(Language::Unknown);
2018   if (const Arg *A = Args.getLastArg(OPT_x)) {
2019     StringRef XValue = A->getValue();
2020 
2021     // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
2022     // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
2023     bool Preprocessed = XValue.consume_back("-cpp-output");
2024     bool ModuleMap = XValue.consume_back("-module-map");
2025     IsHeaderFile = !Preprocessed && !ModuleMap &&
2026                    XValue != "precompiled-header" &&
2027                    XValue.consume_back("-header");
2028 
2029     // Principal languages.
2030     DashX = llvm::StringSwitch<InputKind>(XValue)
2031                 .Case("c", Language::C)
2032                 .Case("cl", Language::OpenCL)
2033                 .Case("cuda", Language::CUDA)
2034                 .Case("hip", Language::HIP)
2035                 .Case("c++", Language::CXX)
2036                 .Case("objective-c", Language::ObjC)
2037                 .Case("objective-c++", Language::ObjCXX)
2038                 .Case("renderscript", Language::RenderScript)
2039                 .Default(Language::Unknown);
2040 
2041     // "objc[++]-cpp-output" is an acceptable synonym for
2042     // "objective-c[++]-cpp-output".
2043     if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
2044       DashX = llvm::StringSwitch<InputKind>(XValue)
2045                   .Case("objc", Language::ObjC)
2046                   .Case("objc++", Language::ObjCXX)
2047                   .Default(Language::Unknown);
2048 
2049     // Some special cases cannot be combined with suffixes.
2050     if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
2051       DashX = llvm::StringSwitch<InputKind>(XValue)
2052                   .Case("cpp-output", InputKind(Language::C).getPreprocessed())
2053                   .Case("assembler-with-cpp", Language::Asm)
2054                   .Cases("ast", "pcm", "precompiled-header",
2055                          InputKind(Language::Unknown, InputKind::Precompiled))
2056                   .Case("ir", Language::LLVM_IR)
2057                   .Default(Language::Unknown);
2058 
2059     if (DashX.isUnknown())
2060       Diags.Report(diag::err_drv_invalid_value)
2061         << A->getAsString(Args) << A->getValue();
2062 
2063     if (Preprocessed)
2064       DashX = DashX.getPreprocessed();
2065     if (ModuleMap)
2066       DashX = DashX.withFormat(InputKind::ModuleMap);
2067   }
2068 
2069   // '-' is the default input if none is given.
2070   std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
2071   Opts.Inputs.clear();
2072   if (Inputs.empty())
2073     Inputs.push_back("-");
2074   for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
2075     InputKind IK = DashX;
2076     if (IK.isUnknown()) {
2077       IK = FrontendOptions::getInputKindForExtension(
2078         StringRef(Inputs[i]).rsplit('.').second);
2079       // FIXME: Warn on this?
2080       if (IK.isUnknown())
2081         IK = Language::C;
2082       // FIXME: Remove this hack.
2083       if (i == 0)
2084         DashX = IK;
2085     }
2086 
2087     bool IsSystem = false;
2088 
2089     // The -emit-module action implicitly takes a module map.
2090     if (Opts.ProgramAction == frontend::GenerateModule &&
2091         IK.getFormat() == InputKind::Source) {
2092       IK = IK.withFormat(InputKind::ModuleMap);
2093       IsSystem = Opts.IsSystemModule;
2094     }
2095 
2096     Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
2097   }
2098 
2099   return DashX;
2100 }
2101 
2102 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
2103                                                  void *MainAddr) {
2104   std::string ClangExecutable =
2105       llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
2106   return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
2107 }
2108 
2109 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
2110                                   const std::string &WorkingDir) {
2111   Opts.Sysroot = std::string(Args.getLastArgValue(OPT_isysroot, "/"));
2112   Opts.Verbose = Args.hasArg(OPT_v);
2113   Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
2114   Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
2115   Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
2116   if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
2117     Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
2118   Opts.ResourceDir = std::string(Args.getLastArgValue(OPT_resource_dir));
2119 
2120   // Canonicalize -fmodules-cache-path before storing it.
2121   SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
2122   if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
2123     if (WorkingDir.empty())
2124       llvm::sys::fs::make_absolute(P);
2125     else
2126       llvm::sys::fs::make_absolute(WorkingDir, P);
2127   }
2128   llvm::sys::path::remove_dots(P);
2129   Opts.ModuleCachePath = std::string(P.str());
2130 
2131   Opts.ModuleUserBuildPath =
2132       std::string(Args.getLastArgValue(OPT_fmodules_user_build_path));
2133   // Only the -fmodule-file=<name>=<file> form.
2134   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2135     StringRef Val = A->getValue();
2136     if (Val.find('=') != StringRef::npos){
2137       auto Split = Val.split('=');
2138       Opts.PrebuiltModuleFiles.insert(
2139           {std::string(Split.first), std::string(Split.second)});
2140     }
2141   }
2142   for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
2143     Opts.AddPrebuiltModulePath(A->getValue());
2144   Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
2145   Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content);
2146   Opts.ModulesValidateDiagnosticOptions =
2147       !Args.hasArg(OPT_fmodules_disable_diagnostic_validation);
2148   Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps);
2149   Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
2150   Opts.ModuleCachePruneInterval =
2151       getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
2152   Opts.ModuleCachePruneAfter =
2153       getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
2154   Opts.ModulesValidateOncePerBuildSession =
2155       Args.hasArg(OPT_fmodules_validate_once_per_build_session);
2156   Opts.BuildSessionTimestamp =
2157       getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
2158   Opts.ModulesValidateSystemHeaders =
2159       Args.hasArg(OPT_fmodules_validate_system_headers);
2160   Opts.ValidateASTInputFilesContent =
2161       Args.hasArg(OPT_fvalidate_ast_input_files_content);
2162   if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
2163     Opts.ModuleFormat = A->getValue();
2164 
2165   for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
2166     StringRef MacroDef = A->getValue();
2167     Opts.ModulesIgnoreMacros.insert(
2168         llvm::CachedHashString(MacroDef.split('=').first));
2169   }
2170 
2171   // Add -I..., -F..., and -index-header-map options in order.
2172   bool IsIndexHeaderMap = false;
2173   bool IsSysrootSpecified =
2174       Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
2175   for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
2176     if (A->getOption().matches(OPT_index_header_map)) {
2177       // -index-header-map applies to the next -I or -F.
2178       IsIndexHeaderMap = true;
2179       continue;
2180     }
2181 
2182     frontend::IncludeDirGroup Group =
2183         IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
2184 
2185     bool IsFramework = A->getOption().matches(OPT_F);
2186     std::string Path = A->getValue();
2187 
2188     if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
2189       SmallString<32> Buffer;
2190       llvm::sys::path::append(Buffer, Opts.Sysroot,
2191                               llvm::StringRef(A->getValue()).substr(1));
2192       Path = std::string(Buffer.str());
2193     }
2194 
2195     Opts.AddPath(Path, Group, IsFramework,
2196                  /*IgnoreSysroot*/ true);
2197     IsIndexHeaderMap = false;
2198   }
2199 
2200   // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
2201   StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
2202   for (const auto *A :
2203        Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
2204     if (A->getOption().matches(OPT_iprefix))
2205       Prefix = A->getValue();
2206     else if (A->getOption().matches(OPT_iwithprefix))
2207       Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
2208     else
2209       Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
2210   }
2211 
2212   for (const auto *A : Args.filtered(OPT_idirafter))
2213     Opts.AddPath(A->getValue(), frontend::After, false, true);
2214   for (const auto *A : Args.filtered(OPT_iquote))
2215     Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
2216   for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
2217     Opts.AddPath(A->getValue(), frontend::System, false,
2218                  !A->getOption().matches(OPT_iwithsysroot));
2219   for (const auto *A : Args.filtered(OPT_iframework))
2220     Opts.AddPath(A->getValue(), frontend::System, true, true);
2221   for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
2222     Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
2223                  /*IgnoreSysRoot=*/false);
2224 
2225   // Add the paths for the various language specific isystem flags.
2226   for (const auto *A : Args.filtered(OPT_c_isystem))
2227     Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
2228   for (const auto *A : Args.filtered(OPT_cxx_isystem))
2229     Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
2230   for (const auto *A : Args.filtered(OPT_objc_isystem))
2231     Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
2232   for (const auto *A : Args.filtered(OPT_objcxx_isystem))
2233     Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
2234 
2235   // Add the internal paths from a driver that detects standard include paths.
2236   for (const auto *A :
2237        Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
2238     frontend::IncludeDirGroup Group = frontend::System;
2239     if (A->getOption().matches(OPT_internal_externc_isystem))
2240       Group = frontend::ExternCSystem;
2241     Opts.AddPath(A->getValue(), Group, false, true);
2242   }
2243 
2244   // Add the path prefixes which are implicitly treated as being system headers.
2245   for (const auto *A :
2246        Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
2247     Opts.AddSystemHeaderPrefix(
2248         A->getValue(), A->getOption().matches(OPT_system_header_prefix));
2249 
2250   for (const auto *A : Args.filtered(OPT_ivfsoverlay))
2251     Opts.AddVFSOverlayFile(A->getValue());
2252 }
2253 
2254 void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
2255                                          const llvm::Triple &T,
2256                                          PreprocessorOptions &PPOpts,
2257                                          LangStandard::Kind LangStd) {
2258   // Set some properties which depend solely on the input kind; it would be nice
2259   // to move these to the language standard, and have the driver resolve the
2260   // input kind + language standard.
2261   //
2262   // FIXME: Perhaps a better model would be for a single source file to have
2263   // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
2264   // simultaneously active?
2265   if (IK.getLanguage() == Language::Asm) {
2266     Opts.AsmPreprocessor = 1;
2267   } else if (IK.isObjectiveC()) {
2268     Opts.ObjC = 1;
2269   }
2270 
2271   if (LangStd == LangStandard::lang_unspecified) {
2272     // Based on the base language, pick one.
2273     switch (IK.getLanguage()) {
2274     case Language::Unknown:
2275     case Language::LLVM_IR:
2276       llvm_unreachable("Invalid input kind!");
2277     case Language::OpenCL:
2278       LangStd = LangStandard::lang_opencl10;
2279       break;
2280     case Language::CUDA:
2281       LangStd = LangStandard::lang_cuda;
2282       break;
2283     case Language::Asm:
2284     case Language::C:
2285 #if defined(CLANG_DEFAULT_STD_C)
2286       LangStd = CLANG_DEFAULT_STD_C;
2287 #else
2288       // The PS4 uses C99 as the default C standard.
2289       if (T.isPS4())
2290         LangStd = LangStandard::lang_gnu99;
2291       else
2292         LangStd = LangStandard::lang_gnu17;
2293 #endif
2294       break;
2295     case Language::ObjC:
2296 #if defined(CLANG_DEFAULT_STD_C)
2297       LangStd = CLANG_DEFAULT_STD_C;
2298 #else
2299       LangStd = LangStandard::lang_gnu11;
2300 #endif
2301       break;
2302     case Language::CXX:
2303     case Language::ObjCXX:
2304 #if defined(CLANG_DEFAULT_STD_CXX)
2305       LangStd = CLANG_DEFAULT_STD_CXX;
2306 #else
2307       LangStd = LangStandard::lang_gnucxx14;
2308 #endif
2309       break;
2310     case Language::RenderScript:
2311       LangStd = LangStandard::lang_c99;
2312       break;
2313     case Language::HIP:
2314       LangStd = LangStandard::lang_hip;
2315       break;
2316     }
2317   }
2318 
2319   const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
2320   Opts.LineComment = Std.hasLineComments();
2321   Opts.C99 = Std.isC99();
2322   Opts.C11 = Std.isC11();
2323   Opts.C17 = Std.isC17();
2324   Opts.C2x = Std.isC2x();
2325   Opts.CPlusPlus = Std.isCPlusPlus();
2326   Opts.CPlusPlus11 = Std.isCPlusPlus11();
2327   Opts.CPlusPlus14 = Std.isCPlusPlus14();
2328   Opts.CPlusPlus17 = Std.isCPlusPlus17();
2329   Opts.CPlusPlus20 = Std.isCPlusPlus20();
2330   Opts.Digraphs = Std.hasDigraphs();
2331   Opts.GNUMode = Std.isGNUMode();
2332   Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus;
2333   Opts.GNUCVersion = 0;
2334   Opts.HexFloats = Std.hasHexFloats();
2335   Opts.ImplicitInt = Std.hasImplicitInt();
2336 
2337   // Set OpenCL Version.
2338   Opts.OpenCL = Std.isOpenCL();
2339   if (LangStd == LangStandard::lang_opencl10)
2340     Opts.OpenCLVersion = 100;
2341   else if (LangStd == LangStandard::lang_opencl11)
2342     Opts.OpenCLVersion = 110;
2343   else if (LangStd == LangStandard::lang_opencl12)
2344     Opts.OpenCLVersion = 120;
2345   else if (LangStd == LangStandard::lang_opencl20)
2346     Opts.OpenCLVersion = 200;
2347   else if (LangStd == LangStandard::lang_openclcpp)
2348     Opts.OpenCLCPlusPlusVersion = 100;
2349 
2350   // OpenCL has some additional defaults.
2351   if (Opts.OpenCL) {
2352     Opts.AltiVec = 0;
2353     Opts.ZVector = 0;
2354     Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::None);
2355     Opts.setDefaultFPContractMode(LangOptions::FPM_On);
2356     Opts.NativeHalfType = 1;
2357     Opts.NativeHalfArgsAndReturns = 1;
2358     Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
2359 
2360     // Include default header file for OpenCL.
2361     if (Opts.IncludeDefaultHeader) {
2362       if (Opts.DeclareOpenCLBuiltins) {
2363         // Only include base header file for builtin types and constants.
2364         PPOpts.Includes.push_back("opencl-c-base.h");
2365       } else {
2366         PPOpts.Includes.push_back("opencl-c.h");
2367       }
2368     }
2369   }
2370 
2371   Opts.HIP = IK.getLanguage() == Language::HIP;
2372   Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP;
2373   if (Opts.CUDA)
2374     // Set default FP_CONTRACT to FAST.
2375     Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
2376 
2377   Opts.RenderScript = IK.getLanguage() == Language::RenderScript;
2378   if (Opts.RenderScript) {
2379     Opts.NativeHalfType = 1;
2380     Opts.NativeHalfArgsAndReturns = 1;
2381   }
2382 
2383   // OpenCL and C++ both have bool, true, false keywords.
2384   Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
2385 
2386   // OpenCL has half keyword
2387   Opts.Half = Opts.OpenCL;
2388 
2389   // C++ has wchar_t keyword.
2390   Opts.WChar = Opts.CPlusPlus;
2391 
2392   Opts.GNUKeywords = Opts.GNUMode;
2393   Opts.CXXOperatorNames = Opts.CPlusPlus;
2394 
2395   Opts.AlignedAllocation = Opts.CPlusPlus17;
2396 
2397   Opts.DollarIdents = !Opts.AsmPreprocessor;
2398 
2399   // Enable [[]] attributes in C++11 and C2x by default.
2400   Opts.DoubleSquareBracketAttributes = Opts.CPlusPlus11 || Opts.C2x;
2401 }
2402 
2403 /// Attempt to parse a visibility value out of the given argument.
2404 static Visibility parseVisibility(Arg *arg, ArgList &args,
2405                                   DiagnosticsEngine &diags) {
2406   StringRef value = arg->getValue();
2407   if (value == "default") {
2408     return DefaultVisibility;
2409   } else if (value == "hidden" || value == "internal") {
2410     return HiddenVisibility;
2411   } else if (value == "protected") {
2412     // FIXME: diagnose if target does not support protected visibility
2413     return ProtectedVisibility;
2414   }
2415 
2416   diags.Report(diag::err_drv_invalid_value)
2417     << arg->getAsString(args) << value;
2418   return DefaultVisibility;
2419 }
2420 
2421 /// Check if input file kind and language standard are compatible.
2422 static bool IsInputCompatibleWithStandard(InputKind IK,
2423                                           const LangStandard &S) {
2424   switch (IK.getLanguage()) {
2425   case Language::Unknown:
2426   case Language::LLVM_IR:
2427     llvm_unreachable("should not parse language flags for this input");
2428 
2429   case Language::C:
2430   case Language::ObjC:
2431   case Language::RenderScript:
2432     return S.getLanguage() == Language::C;
2433 
2434   case Language::OpenCL:
2435     return S.getLanguage() == Language::OpenCL;
2436 
2437   case Language::CXX:
2438   case Language::ObjCXX:
2439     return S.getLanguage() == Language::CXX;
2440 
2441   case Language::CUDA:
2442     // FIXME: What -std= values should be permitted for CUDA compilations?
2443     return S.getLanguage() == Language::CUDA ||
2444            S.getLanguage() == Language::CXX;
2445 
2446   case Language::HIP:
2447     return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
2448 
2449   case Language::Asm:
2450     // Accept (and ignore) all -std= values.
2451     // FIXME: The -std= value is not ignored; it affects the tokenization
2452     // and preprocessing rules if we're preprocessing this asm input.
2453     return true;
2454   }
2455 
2456   llvm_unreachable("unexpected input language");
2457 }
2458 
2459 /// Get language name for given input kind.
2460 static const StringRef GetInputKindName(InputKind IK) {
2461   switch (IK.getLanguage()) {
2462   case Language::C:
2463     return "C";
2464   case Language::ObjC:
2465     return "Objective-C";
2466   case Language::CXX:
2467     return "C++";
2468   case Language::ObjCXX:
2469     return "Objective-C++";
2470   case Language::OpenCL:
2471     return "OpenCL";
2472   case Language::CUDA:
2473     return "CUDA";
2474   case Language::RenderScript:
2475     return "RenderScript";
2476   case Language::HIP:
2477     return "HIP";
2478 
2479   case Language::Asm:
2480     return "Asm";
2481   case Language::LLVM_IR:
2482     return "LLVM IR";
2483 
2484   case Language::Unknown:
2485     break;
2486   }
2487   llvm_unreachable("unknown input language");
2488 }
2489 
2490 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
2491                           const TargetOptions &TargetOpts,
2492                           PreprocessorOptions &PPOpts,
2493                           DiagnosticsEngine &Diags) {
2494   // FIXME: Cleanup per-file based stuff.
2495   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
2496   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
2497     LangStd = LangStandard::getLangKind(A->getValue());
2498     if (LangStd == LangStandard::lang_unspecified) {
2499       Diags.Report(diag::err_drv_invalid_value)
2500         << A->getAsString(Args) << A->getValue();
2501       // Report supported standards with short description.
2502       for (unsigned KindValue = 0;
2503            KindValue != LangStandard::lang_unspecified;
2504            ++KindValue) {
2505         const LangStandard &Std = LangStandard::getLangStandardForKind(
2506           static_cast<LangStandard::Kind>(KindValue));
2507         if (IsInputCompatibleWithStandard(IK, Std)) {
2508           auto Diag = Diags.Report(diag::note_drv_use_standard);
2509           Diag << Std.getName() << Std.getDescription();
2510           unsigned NumAliases = 0;
2511 #define LANGSTANDARD(id, name, lang, desc, features)
2512 #define LANGSTANDARD_ALIAS(id, alias) \
2513           if (KindValue == LangStandard::lang_##id) ++NumAliases;
2514 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
2515 #include "clang/Basic/LangStandards.def"
2516           Diag << NumAliases;
2517 #define LANGSTANDARD(id, name, lang, desc, features)
2518 #define LANGSTANDARD_ALIAS(id, alias) \
2519           if (KindValue == LangStandard::lang_##id) Diag << alias;
2520 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
2521 #include "clang/Basic/LangStandards.def"
2522         }
2523       }
2524     } else {
2525       // Valid standard, check to make sure language and standard are
2526       // compatible.
2527       const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
2528       if (!IsInputCompatibleWithStandard(IK, Std)) {
2529         Diags.Report(diag::err_drv_argument_not_allowed_with)
2530           << A->getAsString(Args) << GetInputKindName(IK);
2531       }
2532     }
2533   }
2534 
2535   if (Args.hasArg(OPT_fno_dllexport_inlines))
2536     Opts.DllExportInlines = false;
2537 
2538   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2539     StringRef Name = A->getValue();
2540     if (Name == "full" || Name == "branch") {
2541       Opts.CFProtectionBranch = 1;
2542     }
2543   }
2544   // -cl-std only applies for OpenCL language standards.
2545   // Override the -std option in this case.
2546   if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
2547     LangStandard::Kind OpenCLLangStd
2548       = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
2549         .Cases("cl", "CL", LangStandard::lang_opencl10)
2550         .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
2551         .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
2552         .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
2553         .Cases("clc++", "CLC++", LangStandard::lang_openclcpp)
2554         .Default(LangStandard::lang_unspecified);
2555 
2556     if (OpenCLLangStd == LangStandard::lang_unspecified) {
2557       Diags.Report(diag::err_drv_invalid_value)
2558         << A->getAsString(Args) << A->getValue();
2559     }
2560     else
2561       LangStd = OpenCLLangStd;
2562   }
2563 
2564   Opts.SYCL = Args.hasArg(options::OPT_fsycl);
2565   Opts.SYCLIsDevice = Opts.SYCL && Args.hasArg(options::OPT_fsycl_is_device);
2566   if (Opts.SYCL) {
2567     // -sycl-std applies to any SYCL source, not only those containing kernels,
2568     // but also those using the SYCL API
2569     if (const Arg *A = Args.getLastArg(OPT_sycl_std_EQ)) {
2570       Opts.SYCLVersion = llvm::StringSwitch<unsigned>(A->getValue())
2571                              .Cases("2017", "1.2.1", "121", "sycl-1.2.1", 2017)
2572                              .Default(0U);
2573 
2574       if (Opts.SYCLVersion == 0U) {
2575         // User has passed an invalid value to the flag, this is an error
2576         Diags.Report(diag::err_drv_invalid_value)
2577             << A->getAsString(Args) << A->getValue();
2578       }
2579     }
2580   }
2581 
2582   Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
2583   Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
2584 
2585   llvm::Triple T(TargetOpts.Triple);
2586   CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd);
2587 
2588   // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
2589   // This option should be deprecated for CL > 1.0 because
2590   // this option was added for compatibility with OpenCL 1.0.
2591   if (Args.getLastArg(OPT_cl_strict_aliasing)
2592        && Opts.OpenCLVersion > 100) {
2593     Diags.Report(diag::warn_option_invalid_ocl_version)
2594         << Opts.getOpenCLVersionTuple().getAsString()
2595         << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
2596   }
2597 
2598   // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
2599   // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
2600   // while a subset (the non-C++ GNU keywords) is provided by GCC's
2601   // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
2602   // name, as it doesn't seem a useful distinction.
2603   Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
2604                                   Opts.GNUKeywords);
2605 
2606   Opts.Digraphs = Args.hasFlag(OPT_fdigraphs, OPT_fno_digraphs, Opts.Digraphs);
2607 
2608   if (Args.hasArg(OPT_fno_operator_names))
2609     Opts.CXXOperatorNames = 0;
2610 
2611   if (Args.hasArg(OPT_fcuda_is_device))
2612     Opts.CUDAIsDevice = 1;
2613 
2614   if (Args.hasArg(OPT_fcuda_allow_variadic_functions))
2615     Opts.CUDAAllowVariadicFunctions = 1;
2616 
2617   if (Args.hasArg(OPT_fno_cuda_host_device_constexpr))
2618     Opts.CUDAHostDeviceConstexpr = 0;
2619 
2620   if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals))
2621     Opts.CUDADeviceApproxTranscendentals = 1;
2622 
2623   Opts.GPURelocatableDeviceCode = Args.hasArg(OPT_fgpu_rdc);
2624   if (Args.hasArg(OPT_fgpu_allow_device_init)) {
2625     if (Opts.HIP)
2626       Opts.GPUAllowDeviceInit = 1;
2627     else
2628       Diags.Report(diag::warn_ignored_hip_only_option)
2629           << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
2630   }
2631   Opts.HIPUseNewLaunchAPI = Args.hasArg(OPT_fhip_new_launch_api);
2632   if (Opts.HIP)
2633     Opts.GPUMaxThreadsPerBlock = getLastArgIntValue(
2634         Args, OPT_gpu_max_threads_per_block_EQ, Opts.GPUMaxThreadsPerBlock);
2635   else if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ))
2636     Diags.Report(diag::warn_ignored_hip_only_option)
2637         << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
2638 
2639   if (Opts.ObjC) {
2640     if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
2641       StringRef value = arg->getValue();
2642       if (Opts.ObjCRuntime.tryParse(value))
2643         Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
2644     }
2645 
2646     if (Args.hasArg(OPT_fobjc_gc_only))
2647       Opts.setGC(LangOptions::GCOnly);
2648     else if (Args.hasArg(OPT_fobjc_gc))
2649       Opts.setGC(LangOptions::HybridGC);
2650     else if (Args.hasArg(OPT_fobjc_arc)) {
2651       Opts.ObjCAutoRefCount = 1;
2652       if (!Opts.ObjCRuntime.allowsARC())
2653         Diags.Report(diag::err_arc_unsupported_on_runtime);
2654     }
2655 
2656     // ObjCWeakRuntime tracks whether the runtime supports __weak, not
2657     // whether the feature is actually enabled.  This is predominantly
2658     // determined by -fobjc-runtime, but we allow it to be overridden
2659     // from the command line for testing purposes.
2660     if (Args.hasArg(OPT_fobjc_runtime_has_weak))
2661       Opts.ObjCWeakRuntime = 1;
2662     else
2663       Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
2664 
2665     // ObjCWeak determines whether __weak is actually enabled.
2666     // Note that we allow -fno-objc-weak to disable this even in ARC mode.
2667     if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
2668       if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
2669         assert(!Opts.ObjCWeak);
2670       } else if (Opts.getGC() != LangOptions::NonGC) {
2671         Diags.Report(diag::err_objc_weak_with_gc);
2672       } else if (!Opts.ObjCWeakRuntime) {
2673         Diags.Report(diag::err_objc_weak_unsupported);
2674       } else {
2675         Opts.ObjCWeak = 1;
2676       }
2677     } else if (Opts.ObjCAutoRefCount) {
2678       Opts.ObjCWeak = Opts.ObjCWeakRuntime;
2679     }
2680 
2681     if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
2682       Opts.ObjCInferRelatedResultType = 0;
2683 
2684     if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
2685       Opts.ObjCSubscriptingLegacyRuntime =
2686         (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
2687   }
2688 
2689   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
2690     // Check that the version has 1 to 3 components and the minor and patch
2691     // versions fit in two decimal digits.
2692     VersionTuple GNUCVer;
2693     bool Invalid = GNUCVer.tryParse(A->getValue());
2694     unsigned Major = GNUCVer.getMajor();
2695     unsigned Minor = GNUCVer.getMinor().getValueOr(0);
2696     unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
2697     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
2698       Diags.Report(diag::err_drv_invalid_value)
2699           << A->getAsString(Args) << A->getValue();
2700     }
2701     Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
2702   }
2703 
2704   if (Args.hasArg(OPT_fgnu89_inline)) {
2705     if (Opts.CPlusPlus)
2706       Diags.Report(diag::err_drv_argument_not_allowed_with)
2707         << "-fgnu89-inline" << GetInputKindName(IK);
2708     else
2709       Opts.GNUInline = 1;
2710   }
2711 
2712   if (Args.hasArg(OPT_fapple_kext)) {
2713     if (!Opts.CPlusPlus)
2714       Diags.Report(diag::warn_c_kext);
2715     else
2716       Opts.AppleKext = 1;
2717   }
2718 
2719   if (Args.hasArg(OPT_print_ivar_layout))
2720     Opts.ObjCGCBitmapPrint = 1;
2721 
2722   if (Args.hasArg(OPT_fno_constant_cfstrings))
2723     Opts.NoConstantCFStrings = 1;
2724   if (const auto *A = Args.getLastArg(OPT_fcf_runtime_abi_EQ))
2725     Opts.CFRuntime =
2726         llvm::StringSwitch<LangOptions::CoreFoundationABI>(A->getValue())
2727             .Cases("unspecified", "standalone", "objc",
2728                    LangOptions::CoreFoundationABI::ObjectiveC)
2729             .Cases("swift", "swift-5.0",
2730                    LangOptions::CoreFoundationABI::Swift5_0)
2731             .Case("swift-4.2", LangOptions::CoreFoundationABI::Swift4_2)
2732             .Case("swift-4.1", LangOptions::CoreFoundationABI::Swift4_1)
2733             .Default(LangOptions::CoreFoundationABI::ObjectiveC);
2734 
2735   if (Args.hasArg(OPT_fzvector))
2736     Opts.ZVector = 1;
2737 
2738   if (Args.hasArg(OPT_pthread))
2739     Opts.POSIXThreads = 1;
2740 
2741   // The value-visibility mode defaults to "default".
2742   if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
2743     Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
2744   } else {
2745     Opts.setValueVisibilityMode(DefaultVisibility);
2746   }
2747 
2748   // The type-visibility mode defaults to the value-visibility mode.
2749   if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
2750     Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
2751   } else {
2752     Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
2753   }
2754 
2755   if (Args.hasArg(OPT_fvisibility_inlines_hidden))
2756     Opts.InlineVisibilityHidden = 1;
2757 
2758   if (Args.hasArg(OPT_fvisibility_global_new_delete_hidden))
2759     Opts.GlobalAllocationFunctionVisibilityHidden = 1;
2760 
2761   if (Args.hasArg(OPT_fapply_global_visibility_to_externs))
2762     Opts.SetVisibilityForExternDecls = 1;
2763 
2764   if (Args.hasArg(OPT_ftrapv)) {
2765     Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
2766     // Set the handler, if one is specified.
2767     Opts.OverflowHandler =
2768         std::string(Args.getLastArgValue(OPT_ftrapv_handler));
2769   }
2770   else if (Args.hasArg(OPT_fwrapv))
2771     Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
2772 
2773   Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
2774   Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
2775   Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
2776   Opts.MSCompatibilityVersion = 0;
2777   if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
2778     VersionTuple VT;
2779     if (VT.tryParse(A->getValue()))
2780       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2781                                                 << A->getValue();
2782     Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
2783                                   VT.getMinor().getValueOr(0) * 100000 +
2784                                   VT.getSubminor().getValueOr(0);
2785   }
2786 
2787   // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
2788   // is specified, or -std is set to a conforming mode.
2789   // Trigraphs are disabled by default in c++1z onwards.
2790   Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17;
2791   Opts.Trigraphs =
2792       Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
2793 
2794   Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
2795                                    OPT_fno_dollars_in_identifiers,
2796                                    Opts.DollarIdents);
2797   Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
2798   Opts.setVtorDispMode(
2799       MSVtorDispMode(getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags)));
2800   Opts.Borland = Args.hasArg(OPT_fborland_extensions);
2801   Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
2802   Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
2803                                    Opts.ConstStrings);
2804   if (Arg *A = Args.getLastArg(OPT_flax_vector_conversions_EQ)) {
2805     using LaxKind = LangOptions::LaxVectorConversionKind;
2806     if (auto Kind = llvm::StringSwitch<Optional<LaxKind>>(A->getValue())
2807                         .Case("none", LaxKind::None)
2808                         .Case("integer", LaxKind::Integer)
2809                         .Case("all", LaxKind::All)
2810                         .Default(llvm::None))
2811       Opts.setLaxVectorConversions(*Kind);
2812     else
2813       Diags.Report(diag::err_drv_invalid_value)
2814           << A->getAsString(Args) << A->getValue();
2815   }
2816   if (Args.hasArg(OPT_fno_threadsafe_statics))
2817     Opts.ThreadsafeStatics = 0;
2818   Opts.Exceptions = Args.hasArg(OPT_fexceptions);
2819   Opts.IgnoreExceptions = Args.hasArg(OPT_fignore_exceptions);
2820   Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
2821   Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
2822 
2823   // -ffixed-point
2824   Opts.FixedPoint =
2825       Args.hasFlag(OPT_ffixed_point, OPT_fno_fixed_point, /*Default=*/false) &&
2826       !Opts.CPlusPlus;
2827   Opts.PaddingOnUnsignedFixedPoint =
2828       Args.hasFlag(OPT_fpadding_on_unsigned_fixed_point,
2829                    OPT_fno_padding_on_unsigned_fixed_point,
2830                    /*Default=*/false) &&
2831       Opts.FixedPoint;
2832 
2833   // Handle exception personalities
2834   Arg *A = Args.getLastArg(
2835       options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
2836       options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
2837   if (A) {
2838     const Option &Opt = A->getOption();
2839     llvm::Triple T(TargetOpts.Triple);
2840     if (T.isWindowsMSVCEnvironment())
2841       Diags.Report(diag::err_fe_invalid_exception_model)
2842           << Opt.getName() << T.str();
2843 
2844     Opts.SjLjExceptions = Opt.matches(options::OPT_fsjlj_exceptions);
2845     Opts.SEHExceptions = Opt.matches(options::OPT_fseh_exceptions);
2846     Opts.DWARFExceptions = Opt.matches(options::OPT_fdwarf_exceptions);
2847     Opts.WasmExceptions = Opt.matches(options::OPT_fwasm_exceptions);
2848   }
2849 
2850   Opts.ExternCNoUnwind = Args.hasArg(OPT_fexternc_nounwind);
2851   Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
2852 
2853   Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti);
2854   Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data);
2855   Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
2856     && Opts.OpenCLVersion == 200);
2857   Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
2858   Opts.Coroutines = Opts.CPlusPlus20 || Args.hasArg(OPT_fcoroutines_ts);
2859 
2860   Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
2861     Args.hasArg(OPT_fconvergent_functions);
2862 
2863   Opts.DoubleSquareBracketAttributes =
2864       Args.hasFlag(OPT_fdouble_square_bracket_attributes,
2865                    OPT_fno_double_square_bracket_attributes,
2866                    Opts.DoubleSquareBracketAttributes);
2867 
2868   Opts.CPlusPlusModules = Opts.CPlusPlus20;
2869   Opts.ModulesTS = Args.hasArg(OPT_fmodules_ts);
2870   Opts.Modules =
2871       Args.hasArg(OPT_fmodules) || Opts.ModulesTS || Opts.CPlusPlusModules;
2872   Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse);
2873   Opts.ModulesDeclUse =
2874       Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse;
2875   // FIXME: We only need this in C++ modules / Modules TS if we might textually
2876   // enter a different module (eg, when building a header unit).
2877   Opts.ModulesLocalVisibility =
2878       Args.hasArg(OPT_fmodules_local_submodule_visibility) || Opts.ModulesTS ||
2879       Opts.CPlusPlusModules;
2880   Opts.ModulesCodegen = Args.hasArg(OPT_fmodules_codegen);
2881   Opts.ModulesDebugInfo = Args.hasArg(OPT_fmodules_debuginfo);
2882   Opts.ModulesSearchAll = Opts.Modules &&
2883     !Args.hasArg(OPT_fno_modules_search_all) &&
2884     Args.hasArg(OPT_fmodules_search_all);
2885   Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
2886   Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules);
2887   Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
2888   Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
2889   Opts.Char8 = Args.hasFlag(OPT_fchar8__t, OPT_fno_char8__t, Opts.CPlusPlus20);
2890   if (const Arg *A = Args.getLastArg(OPT_fwchar_type_EQ)) {
2891     Opts.WCharSize = llvm::StringSwitch<unsigned>(A->getValue())
2892                          .Case("char", 1)
2893                          .Case("short", 2)
2894                          .Case("int", 4)
2895                          .Default(0);
2896     if (Opts.WCharSize == 0)
2897       Diags.Report(diag::err_fe_invalid_wchar_type) << A->getValue();
2898   }
2899   Opts.WCharIsSigned = Args.hasFlag(OPT_fsigned_wchar, OPT_fno_signed_wchar, true);
2900   Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
2901   Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
2902   Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
2903   if (!Opts.NoBuiltin)
2904     getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
2905   Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
2906   Opts.RelaxedTemplateTemplateArgs =
2907       Args.hasArg(OPT_frelaxed_template_template_args);
2908   Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation);
2909   Opts.AlignedAllocation =
2910       Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation,
2911                    Opts.AlignedAllocation);
2912   Opts.AlignedAllocationUnavailable =
2913       Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable);
2914   Opts.NewAlignOverride =
2915       getLastArgIntValue(Args, OPT_fnew_alignment_EQ, 0, Diags);
2916   if (Opts.NewAlignOverride && !llvm::isPowerOf2_32(Opts.NewAlignOverride)) {
2917     Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
2918     Diags.Report(diag::err_fe_invalid_alignment) << A->getAsString(Args)
2919                                                  << A->getValue();
2920     Opts.NewAlignOverride = 0;
2921   }
2922   Opts.ConceptSatisfactionCaching =
2923       !Args.hasArg(OPT_fno_concept_satisfaction_caching);
2924   if (Args.hasArg(OPT_fconcepts_ts))
2925     Diags.Report(diag::warn_fe_concepts_ts_flag);
2926   // Recovery AST still heavily relies on dependent-type machinery.
2927   Opts.RecoveryAST =
2928       Args.hasFlag(OPT_frecovery_ast, OPT_fno_recovery_ast, Opts.CPlusPlus);
2929   Opts.RecoveryASTType =
2930       Args.hasFlag(OPT_frecovery_ast_type, OPT_fno_recovery_ast_type, false);
2931   Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
2932   Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
2933   Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
2934   Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
2935   Opts.InstantiationDepth =
2936       getLastArgIntValue(Args, OPT_ftemplate_depth, 1024, Diags);
2937   Opts.ArrowDepth =
2938       getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags);
2939   Opts.ConstexprCallDepth =
2940       getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
2941   Opts.ConstexprStepLimit =
2942       getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
2943   Opts.EnableNewConstInterp =
2944       Args.hasArg(OPT_fexperimental_new_constant_interpreter);
2945   Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
2946   Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
2947   Opts.NumLargeByValueCopy =
2948       getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
2949   Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
2950   Opts.ObjCConstantStringClass =
2951       std::string(Args.getLastArgValue(OPT_fconstant_string_class));
2952   Opts.ObjCDefaultSynthProperties =
2953     !Args.hasArg(OPT_disable_objc_default_synthesize_properties);
2954   Opts.EncodeExtendedBlockSig =
2955     Args.hasArg(OPT_fencode_extended_block_signature);
2956   Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
2957   Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
2958   Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
2959   Opts.AlignDouble = Args.hasArg(OPT_malign_double);
2960   Opts.DoubleSize = getLastArgIntValue(Args, OPT_mdouble_EQ, 0, Diags);
2961   Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128)
2962                             ? 128
2963                             : Args.hasArg(OPT_mlong_double_64) ? 64 : 0;
2964   Opts.PPCIEEELongDouble = Args.hasArg(OPT_mabi_EQ_ieeelongdouble);
2965   Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
2966   Opts.ROPI = Args.hasArg(OPT_fropi);
2967   Opts.RWPI = Args.hasArg(OPT_frwpi);
2968   Opts.PIE = Args.hasArg(OPT_pic_is_pie);
2969   Opts.Static = Args.hasArg(OPT_static_define);
2970   Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
2971   Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
2972                         || Args.hasArg(OPT_fdump_record_layouts);
2973   Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
2974   Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
2975   Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
2976   Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
2977   Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
2978   if (Opts.FastRelaxedMath)
2979     Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
2980   Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
2981   Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
2982   Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
2983   Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
2984   Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
2985   Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
2986   Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
2987   Opts.ModuleName = std::string(Args.getLastArgValue(OPT_fmodule_name_EQ));
2988   Opts.CurrentModule = Opts.ModuleName;
2989   Opts.AppExt = Args.hasArg(OPT_fapplication_extension);
2990   Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
2991   llvm::sort(Opts.ModuleFeatures);
2992   Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type);
2993   Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns);
2994   // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns
2995   // is enabled.
2996   Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns)
2997                             | Opts.NativeHalfArgsAndReturns;
2998   Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm);
2999   Opts.Cmse = Args.hasArg(OPT_mcmse); // Armv8-M Security Extensions
3000 
3001   // __declspec is enabled by default for the PS4 by the driver, and also
3002   // enabled for Microsoft Extensions or Borland Extensions, here.
3003   //
3004   // FIXME: __declspec is also currently enabled for CUDA, but isn't really a
3005   // CUDA extension. However, it is required for supporting
3006   // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has
3007   // been rewritten in terms of something more generic, remove the Opts.CUDA
3008   // term here.
3009   Opts.DeclSpecKeyword =
3010       Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec,
3011                    (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA));
3012 
3013   if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) {
3014     switch (llvm::StringSwitch<unsigned>(A->getValue())
3015       .Case("target", LangOptions::ASMM_Target)
3016       .Case("no", LangOptions::ASMM_Off)
3017       .Case("yes", LangOptions::ASMM_On)
3018       .Default(255)) {
3019     default:
3020       Diags.Report(diag::err_drv_invalid_value)
3021         << "-faddress-space-map-mangling=" << A->getValue();
3022       break;
3023     case LangOptions::ASMM_Target:
3024       Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target);
3025       break;
3026     case LangOptions::ASMM_On:
3027       Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On);
3028       break;
3029     case LangOptions::ASMM_Off:
3030       Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off);
3031       break;
3032     }
3033   }
3034 
3035   if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) {
3036     LangOptions::PragmaMSPointersToMembersKind InheritanceModel =
3037         llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>(
3038             A->getValue())
3039             .Case("single",
3040                   LangOptions::PPTMK_FullGeneralitySingleInheritance)
3041             .Case("multiple",
3042                   LangOptions::PPTMK_FullGeneralityMultipleInheritance)
3043             .Case("virtual",
3044                   LangOptions::PPTMK_FullGeneralityVirtualInheritance)
3045             .Default(LangOptions::PPTMK_BestCase);
3046     if (InheritanceModel == LangOptions::PPTMK_BestCase)
3047       Diags.Report(diag::err_drv_invalid_value)
3048           << "-fms-memptr-rep=" << A->getValue();
3049 
3050     Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel);
3051   }
3052 
3053   // Check for MS default calling conventions being specified.
3054   if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
3055     LangOptions::DefaultCallingConvention DefaultCC =
3056         llvm::StringSwitch<LangOptions::DefaultCallingConvention>(A->getValue())
3057             .Case("cdecl", LangOptions::DCC_CDecl)
3058             .Case("fastcall", LangOptions::DCC_FastCall)
3059             .Case("stdcall", LangOptions::DCC_StdCall)
3060             .Case("vectorcall", LangOptions::DCC_VectorCall)
3061             .Case("regcall", LangOptions::DCC_RegCall)
3062             .Default(LangOptions::DCC_None);
3063     if (DefaultCC == LangOptions::DCC_None)
3064       Diags.Report(diag::err_drv_invalid_value)
3065           << "-fdefault-calling-conv=" << A->getValue();
3066 
3067     llvm::Triple T(TargetOpts.Triple);
3068     llvm::Triple::ArchType Arch = T.getArch();
3069     bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
3070                       DefaultCC == LangOptions::DCC_StdCall) &&
3071                      Arch != llvm::Triple::x86;
3072     emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
3073                   DefaultCC == LangOptions::DCC_RegCall) &&
3074                  !T.isX86();
3075     if (emitError)
3076       Diags.Report(diag::err_drv_argument_not_allowed_with)
3077           << A->getSpelling() << T.getTriple();
3078     else
3079       Opts.setDefaultCallingConv(DefaultCC);
3080   }
3081 
3082   Opts.SemanticInterposition = Args.hasArg(OPT_fsemantic_interposition);
3083   // An explicit -fno-semantic-interposition infers dso_local.
3084   Opts.ExplicitNoSemanticInterposition =
3085       Args.hasArg(OPT_fno_semantic_interposition);
3086 
3087   // -mrtd option
3088   if (Arg *A = Args.getLastArg(OPT_mrtd)) {
3089     if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
3090       Diags.Report(diag::err_drv_argument_not_allowed_with)
3091           << A->getSpelling() << "-fdefault-calling-conv";
3092     else {
3093       llvm::Triple T(TargetOpts.Triple);
3094       if (T.getArch() != llvm::Triple::x86)
3095         Diags.Report(diag::err_drv_argument_not_allowed_with)
3096             << A->getSpelling() << T.getTriple();
3097       else
3098         Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
3099     }
3100   }
3101 
3102   // Check if -fopenmp is specified and set default version to 5.0.
3103   Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 50 : 0;
3104   // Check if -fopenmp-simd is specified.
3105   bool IsSimdSpecified =
3106       Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
3107                    /*Default=*/false);
3108   Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
3109   Opts.OpenMPUseTLS =
3110       Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
3111   Opts.OpenMPIsDevice =
3112       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
3113   Opts.OpenMPIRBuilder =
3114       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
3115   bool IsTargetSpecified =
3116       Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
3117 
3118   if (Opts.OpenMP || Opts.OpenMPSimd) {
3119     if (int Version = getLastArgIntValue(
3120             Args, OPT_fopenmp_version_EQ,
3121             (IsSimdSpecified || IsTargetSpecified) ? 50 : Opts.OpenMP, Diags))
3122       Opts.OpenMP = Version;
3123     // Provide diagnostic when a given target is not expected to be an OpenMP
3124     // device or host.
3125     if (!Opts.OpenMPIsDevice) {
3126       switch (T.getArch()) {
3127       default:
3128         break;
3129       // Add unsupported host targets here:
3130       case llvm::Triple::nvptx:
3131       case llvm::Triple::nvptx64:
3132         Diags.Report(diag::err_drv_omp_host_target_not_supported)
3133             << TargetOpts.Triple;
3134         break;
3135       }
3136     }
3137   }
3138 
3139   // Set the flag to prevent the implementation from emitting device exception
3140   // handling code for those requiring so.
3141   if ((Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN())) ||
3142       Opts.OpenCLCPlusPlus) {
3143     Opts.Exceptions = 0;
3144     Opts.CXXExceptions = 0;
3145   }
3146   if (Opts.OpenMPIsDevice && T.isNVPTX()) {
3147     Opts.OpenMPCUDANumSMs =
3148         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
3149                            Opts.OpenMPCUDANumSMs, Diags);
3150     Opts.OpenMPCUDABlocksPerSM =
3151         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
3152                            Opts.OpenMPCUDABlocksPerSM, Diags);
3153     Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
3154         Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3155         Opts.OpenMPCUDAReductionBufNum, Diags);
3156   }
3157 
3158   // Prevent auto-widening the representation of loop counters during an
3159   // OpenMP collapse clause.
3160   Opts.OpenMPOptimisticCollapse =
3161       Args.hasArg(options::OPT_fopenmp_optimistic_collapse) ? 1 : 0;
3162 
3163   // Get the OpenMP target triples if any.
3164   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
3165 
3166     for (unsigned i = 0; i < A->getNumValues(); ++i) {
3167       llvm::Triple TT(A->getValue(i));
3168 
3169       if (TT.getArch() == llvm::Triple::UnknownArch ||
3170           !(TT.getArch() == llvm::Triple::aarch64 ||
3171             TT.getArch() == llvm::Triple::ppc ||
3172             TT.getArch() == llvm::Triple::ppc64 ||
3173             TT.getArch() == llvm::Triple::ppc64le ||
3174             TT.getArch() == llvm::Triple::nvptx ||
3175             TT.getArch() == llvm::Triple::nvptx64 ||
3176             TT.getArch() == llvm::Triple::amdgcn ||
3177             TT.getArch() == llvm::Triple::x86 ||
3178             TT.getArch() == llvm::Triple::x86_64))
3179         Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
3180       else
3181         Opts.OMPTargetTriples.push_back(TT);
3182     }
3183   }
3184 
3185   // Get OpenMP host file path if any and report if a non existent file is
3186   // found
3187   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
3188     Opts.OMPHostIRFile = A->getValue();
3189     if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
3190       Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
3191           << Opts.OMPHostIRFile;
3192   }
3193 
3194   // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
3195   Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
3196                         Args.hasArg(options::OPT_fopenmp_cuda_mode);
3197 
3198   // Set CUDA support for parallel execution of target regions for OpenMP target
3199   // NVPTX/AMDGCN if specified in options.
3200   Opts.OpenMPCUDATargetParallel =
3201       Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
3202       Args.hasArg(options::OPT_fopenmp_cuda_parallel_target_regions);
3203 
3204   // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
3205   Opts.OpenMPCUDAForceFullRuntime =
3206       Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
3207       Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime);
3208 
3209   // Record whether the __DEPRECATED define was requested.
3210   Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
3211                                  OPT_fno_deprecated_macro,
3212                                  Opts.Deprecated);
3213 
3214   // FIXME: Eliminate this dependency.
3215   unsigned Opt = getOptimizationLevel(Args, IK, Diags),
3216        OptSize = getOptimizationLevelSize(Args);
3217   Opts.Optimize = Opt != 0;
3218   Opts.OptimizeSize = OptSize != 0;
3219 
3220   // This is the __NO_INLINE__ define, which just depends on things like the
3221   // optimization level and -fno-inline, not actually whether the backend has
3222   // inlining enabled.
3223   Opts.NoInlineDefine = !Opts.Optimize;
3224   if (Arg *InlineArg = Args.getLastArg(
3225           options::OPT_finline_functions, options::OPT_finline_hint_functions,
3226           options::OPT_fno_inline_functions, options::OPT_fno_inline))
3227     if (InlineArg->getOption().matches(options::OPT_fno_inline))
3228       Opts.NoInlineDefine = true;
3229 
3230   Opts.FastMath =
3231       Args.hasArg(OPT_ffast_math) || Args.hasArg(OPT_cl_fast_relaxed_math);
3232   Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
3233                         Args.hasArg(OPT_ffast_math) ||
3234                         Args.hasArg(OPT_cl_finite_math_only) ||
3235                         Args.hasArg(OPT_cl_fast_relaxed_math);
3236   Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
3237                       Args.hasArg(OPT_ffast_math) ||
3238                       Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
3239                       Args.hasArg(OPT_cl_fast_relaxed_math);
3240   Opts.AllowFPReassoc = Args.hasArg(OPT_mreassociate) ||
3241                         Args.hasArg(OPT_menable_unsafe_fp_math) ||
3242                         Args.hasArg(OPT_ffast_math) ||
3243                         Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
3244                         Args.hasArg(OPT_cl_fast_relaxed_math);
3245   Opts.NoHonorNaNs =
3246       Args.hasArg(OPT_menable_no_nans) || Args.hasArg(OPT_ffinite_math_only) ||
3247       Args.hasArg(OPT_ffast_math) || Args.hasArg(OPT_cl_finite_math_only) ||
3248       Args.hasArg(OPT_cl_fast_relaxed_math);
3249   Opts.NoHonorInfs = Args.hasArg(OPT_menable_no_infinities) ||
3250                      Args.hasArg(OPT_ffinite_math_only) ||
3251                      Args.hasArg(OPT_ffast_math) ||
3252                      Args.hasArg(OPT_cl_finite_math_only) ||
3253                      Args.hasArg(OPT_cl_fast_relaxed_math);
3254   Opts.NoSignedZero = Args.hasArg(OPT_fno_signed_zeros) ||
3255                       Args.hasArg(OPT_menable_unsafe_fp_math) ||
3256                       Args.hasArg(OPT_ffast_math) ||
3257                       Args.hasArg(OPT_cl_no_signed_zeros) ||
3258                       Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
3259                       Args.hasArg(OPT_cl_fast_relaxed_math);
3260   Opts.AllowRecip = Args.hasArg(OPT_freciprocal_math) ||
3261                     Args.hasArg(OPT_menable_unsafe_fp_math) ||
3262                     Args.hasArg(OPT_ffast_math) ||
3263                     Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
3264                     Args.hasArg(OPT_cl_fast_relaxed_math);
3265   // Currently there's no clang option to enable this individually
3266   Opts.ApproxFunc = Args.hasArg(OPT_menable_unsafe_fp_math) ||
3267                     Args.hasArg(OPT_ffast_math) ||
3268                     Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
3269                     Args.hasArg(OPT_cl_fast_relaxed_math);
3270 
3271   if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
3272     StringRef Val = A->getValue();
3273     if (Val == "fast")
3274       Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3275     else if (Val == "on")
3276       Opts.setDefaultFPContractMode(LangOptions::FPM_On);
3277     else if (Val == "off")
3278       Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
3279     else
3280       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3281   }
3282 
3283   if (Args.hasArg(OPT_fexperimental_strict_floating_point))
3284     Opts.ExpStrictFP = true;
3285 
3286   auto FPRM = llvm::RoundingMode::NearestTiesToEven;
3287   if (Args.hasArg(OPT_frounding_math)) {
3288     FPRM = llvm::RoundingMode::Dynamic;
3289   }
3290   Opts.setFPRoundingMode(FPRM);
3291 
3292   if (Args.hasArg(OPT_ftrapping_math)) {
3293     Opts.setFPExceptionMode(LangOptions::FPE_Strict);
3294   }
3295 
3296   if (Args.hasArg(OPT_fno_trapping_math)) {
3297     Opts.setFPExceptionMode(LangOptions::FPE_Ignore);
3298   }
3299 
3300   LangOptions::FPExceptionModeKind FPEB = LangOptions::FPE_Ignore;
3301   if (Arg *A = Args.getLastArg(OPT_ffp_exception_behavior_EQ)) {
3302     StringRef Val = A->getValue();
3303     if (Val.equals("ignore"))
3304       FPEB = LangOptions::FPE_Ignore;
3305     else if (Val.equals("maytrap"))
3306       FPEB = LangOptions::FPE_MayTrap;
3307     else if (Val.equals("strict"))
3308       FPEB = LangOptions::FPE_Strict;
3309     else
3310       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3311   }
3312   Opts.setFPExceptionMode(FPEB);
3313 
3314   Opts.RetainCommentsFromSystemHeaders =
3315       Args.hasArg(OPT_fretain_comments_from_system_headers);
3316 
3317   unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
3318   switch (SSP) {
3319   default:
3320     Diags.Report(diag::err_drv_invalid_value)
3321       << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
3322     break;
3323   case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
3324   case 1: Opts.setStackProtector(LangOptions::SSPOn);  break;
3325   case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
3326   case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
3327   }
3328 
3329   if (Arg *A = Args.getLastArg(OPT_ftrivial_auto_var_init)) {
3330     StringRef Val = A->getValue();
3331     if (Val == "uninitialized")
3332       Opts.setTrivialAutoVarInit(
3333           LangOptions::TrivialAutoVarInitKind::Uninitialized);
3334     else if (Val == "zero")
3335       Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Zero);
3336     else if (Val == "pattern")
3337       Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Pattern);
3338     else
3339       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3340   }
3341 
3342   if (Arg *A = Args.getLastArg(OPT_ftrivial_auto_var_init_stop_after)) {
3343     int Val = std::stoi(A->getValue());
3344     Opts.TrivialAutoVarInitStopAfter = Val;
3345   }
3346 
3347   // Parse -fsanitize= arguments.
3348   parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3349                       Diags, Opts.Sanitize);
3350   // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
3351   Opts.SanitizeAddressFieldPadding =
3352       getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
3353   Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
3354   std::vector<std::string> systemBlacklists =
3355       Args.getAllArgValues(OPT_fsanitize_system_blacklist);
3356   Opts.SanitizerBlacklistFiles.insert(Opts.SanitizerBlacklistFiles.end(),
3357                                       systemBlacklists.begin(),
3358                                       systemBlacklists.end());
3359 
3360   // -fxray-instrument
3361   Opts.XRayInstrument = Args.hasArg(OPT_fxray_instrument);
3362   Opts.XRayAlwaysEmitCustomEvents =
3363       Args.hasArg(OPT_fxray_always_emit_customevents);
3364   Opts.XRayAlwaysEmitTypedEvents =
3365       Args.hasArg(OPT_fxray_always_emit_typedevents);
3366 
3367   // -fxray-{always,never}-instrument= filenames.
3368   Opts.XRayAlwaysInstrumentFiles =
3369       Args.getAllArgValues(OPT_fxray_always_instrument);
3370   Opts.XRayNeverInstrumentFiles =
3371       Args.getAllArgValues(OPT_fxray_never_instrument);
3372   Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list);
3373 
3374   // -fforce-emit-vtables
3375   Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
3376 
3377   // -fallow-editor-placeholders
3378   Opts.AllowEditorPlaceholders = Args.hasArg(OPT_fallow_editor_placeholders);
3379 
3380   Opts.RegisterStaticDestructors = !Args.hasArg(OPT_fno_cxx_static_destructors);
3381 
3382   if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
3383     Opts.setClangABICompat(LangOptions::ClangABI::Latest);
3384 
3385     StringRef Ver = A->getValue();
3386     std::pair<StringRef, StringRef> VerParts = Ver.split('.');
3387     unsigned Major, Minor = 0;
3388 
3389     // Check the version number is valid: either 3.x (0 <= x <= 9) or
3390     // y or y.0 (4 <= y <= current version).
3391     if (!VerParts.first.startswith("0") &&
3392         !VerParts.first.getAsInteger(10, Major) &&
3393         3 <= Major && Major <= CLANG_VERSION_MAJOR &&
3394         (Major == 3 ? VerParts.second.size() == 1 &&
3395                       !VerParts.second.getAsInteger(10, Minor)
3396                     : VerParts.first.size() == Ver.size() ||
3397                       VerParts.second == "0")) {
3398       // Got a valid version number.
3399       if (Major == 3 && Minor <= 8)
3400         Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
3401       else if (Major <= 4)
3402         Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
3403       else if (Major <= 6)
3404         Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
3405       else if (Major <= 7)
3406         Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
3407       else if (Major <= 9)
3408         Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
3409     } else if (Ver != "latest") {
3410       Diags.Report(diag::err_drv_invalid_value)
3411           << A->getAsString(Args) << A->getValue();
3412     }
3413   }
3414 
3415   Opts.CompleteMemberPointers = Args.hasArg(OPT_fcomplete_member_pointers);
3416   Opts.BuildingPCHWithObjectFile = Args.hasArg(OPT_building_pch_with_obj);
3417   Opts.PCHInstantiateTemplates = Args.hasArg(OPT_fpch_instantiate_templates);
3418 
3419   Opts.MatrixTypes = Args.hasArg(OPT_fenable_matrix);
3420 
3421   Opts.MaxTokens = getLastArgIntValue(Args, OPT_fmax_tokens_EQ, 0, Diags);
3422 
3423   if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
3424     StringRef SignScope = A->getValue();
3425 
3426     if (SignScope.equals_lower("none"))
3427       Opts.setSignReturnAddressScope(
3428           LangOptions::SignReturnAddressScopeKind::None);
3429     else if (SignScope.equals_lower("all"))
3430       Opts.setSignReturnAddressScope(
3431           LangOptions::SignReturnAddressScopeKind::All);
3432     else if (SignScope.equals_lower("non-leaf"))
3433       Opts.setSignReturnAddressScope(
3434           LangOptions::SignReturnAddressScopeKind::NonLeaf);
3435     else
3436       Diags.Report(diag::err_drv_invalid_value)
3437           << A->getAsString(Args) << SignScope;
3438 
3439     if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
3440       StringRef SignKey = A->getValue();
3441       if (!SignScope.empty() && !SignKey.empty()) {
3442         if (SignKey.equals_lower("a_key"))
3443           Opts.setSignReturnAddressKey(
3444               LangOptions::SignReturnAddressKeyKind::AKey);
3445         else if (SignKey.equals_lower("b_key"))
3446           Opts.setSignReturnAddressKey(
3447               LangOptions::SignReturnAddressKeyKind::BKey);
3448         else
3449           Diags.Report(diag::err_drv_invalid_value)
3450               << A->getAsString(Args) << SignKey;
3451       }
3452     }
3453   }
3454 
3455   Opts.BranchTargetEnforcement = Args.hasArg(OPT_mbranch_target_enforce);
3456   Opts.SpeculativeLoadHardening = Args.hasArg(OPT_mspeculative_load_hardening);
3457 
3458   Opts.CompatibilityQualifiedIdBlockParamTypeChecking =
3459       Args.hasArg(OPT_fcompatibility_qualified_id_block_param_type_checking);
3460 
3461   Opts.RelativeCXXABIVTables =
3462       Args.hasFlag(OPT_fexperimental_relative_cxx_abi_vtables,
3463                    OPT_fno_experimental_relative_cxx_abi_vtables,
3464                    /*default=*/false);
3465 }
3466 
3467 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
3468   switch (Action) {
3469   case frontend::ASTDeclList:
3470   case frontend::ASTDump:
3471   case frontend::ASTPrint:
3472   case frontend::ASTView:
3473   case frontend::EmitAssembly:
3474   case frontend::EmitBC:
3475   case frontend::EmitHTML:
3476   case frontend::EmitLLVM:
3477   case frontend::EmitLLVMOnly:
3478   case frontend::EmitCodeGenOnly:
3479   case frontend::EmitObj:
3480   case frontend::FixIt:
3481   case frontend::GenerateModule:
3482   case frontend::GenerateModuleInterface:
3483   case frontend::GenerateHeaderModule:
3484   case frontend::GeneratePCH:
3485   case frontend::GenerateInterfaceStubs:
3486   case frontend::ParseSyntaxOnly:
3487   case frontend::ModuleFileInfo:
3488   case frontend::VerifyPCH:
3489   case frontend::PluginAction:
3490   case frontend::RewriteObjC:
3491   case frontend::RewriteTest:
3492   case frontend::RunAnalysis:
3493   case frontend::TemplightDump:
3494   case frontend::MigrateSource:
3495     return false;
3496 
3497   case frontend::DumpCompilerOptions:
3498   case frontend::DumpRawTokens:
3499   case frontend::DumpTokens:
3500   case frontend::InitOnly:
3501   case frontend::PrintPreamble:
3502   case frontend::PrintPreprocessedInput:
3503   case frontend::RewriteMacros:
3504   case frontend::RunPreprocessorOnly:
3505   case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
3506     return true;
3507   }
3508   llvm_unreachable("invalid frontend action");
3509 }
3510 
3511 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
3512                                   DiagnosticsEngine &Diags,
3513                                   frontend::ActionKind Action) {
3514   Opts.ImplicitPCHInclude = std::string(Args.getLastArgValue(OPT_include_pch));
3515   Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
3516                         Args.hasArg(OPT_pch_through_hdrstop_use);
3517   Opts.PCHWithHdrStopCreate = Args.hasArg(OPT_pch_through_hdrstop_create);
3518   Opts.PCHThroughHeader =
3519       std::string(Args.getLastArgValue(OPT_pch_through_header_EQ));
3520   Opts.UsePredefines = !Args.hasArg(OPT_undef);
3521   Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
3522   Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
3523   Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors);
3524 
3525   Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
3526   for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
3527     Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
3528 
3529   for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
3530     auto Split = StringRef(A).split('=');
3531     Opts.MacroPrefixMap.insert(
3532         {std::string(Split.first), std::string(Split.second)});
3533   }
3534 
3535   if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
3536     StringRef Value(A->getValue());
3537     size_t Comma = Value.find(',');
3538     unsigned Bytes = 0;
3539     unsigned EndOfLine = 0;
3540 
3541     if (Comma == StringRef::npos ||
3542         Value.substr(0, Comma).getAsInteger(10, Bytes) ||
3543         Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
3544       Diags.Report(diag::err_drv_preamble_format);
3545     else {
3546       Opts.PrecompiledPreambleBytes.first = Bytes;
3547       Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
3548     }
3549   }
3550 
3551   // Add the __CET__ macro if a CFProtection option is set.
3552   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3553     StringRef Name = A->getValue();
3554     if (Name == "branch")
3555       Opts.addMacroDef("__CET__=1");
3556     else if (Name == "return")
3557       Opts.addMacroDef("__CET__=2");
3558     else if (Name == "full")
3559       Opts.addMacroDef("__CET__=3");
3560   }
3561 
3562   // Add macros from the command line.
3563   for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
3564     if (A->getOption().matches(OPT_D))
3565       Opts.addMacroDef(A->getValue());
3566     else
3567       Opts.addMacroUndef(A->getValue());
3568   }
3569 
3570   Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
3571 
3572   // Add the ordered list of -includes.
3573   for (const auto *A : Args.filtered(OPT_include))
3574     Opts.Includes.emplace_back(A->getValue());
3575 
3576   for (const auto *A : Args.filtered(OPT_chain_include))
3577     Opts.ChainedIncludes.emplace_back(A->getValue());
3578 
3579   for (const auto *A : Args.filtered(OPT_remap_file)) {
3580     std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
3581 
3582     if (Split.second.empty()) {
3583       Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
3584       continue;
3585     }
3586 
3587     Opts.addRemappedFile(Split.first, Split.second);
3588   }
3589 
3590   if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
3591     StringRef Name = A->getValue();
3592     unsigned Library = llvm::StringSwitch<unsigned>(Name)
3593       .Case("libc++", ARCXX_libcxx)
3594       .Case("libstdc++", ARCXX_libstdcxx)
3595       .Case("none", ARCXX_nolib)
3596       .Default(~0U);
3597     if (Library == ~0U)
3598       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
3599     else
3600       Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library;
3601   }
3602 
3603   // Always avoid lexing editor placeholders when we're just running the
3604   // preprocessor as we never want to emit the
3605   // "editor placeholder in source file" error in PP only mode.
3606   if (isStrictlyPreprocessorAction(Action))
3607     Opts.LexEditorPlaceholders = false;
3608 
3609   Opts.SetUpStaticAnalyzer = Args.hasArg(OPT_setup_static_analyzer);
3610   Opts.DisablePragmaDebugCrash = Args.hasArg(OPT_disable_pragma_debug_crash);
3611 }
3612 
3613 static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
3614                                         ArgList &Args,
3615                                         frontend::ActionKind Action) {
3616   if (isStrictlyPreprocessorAction(Action))
3617     Opts.ShowCPP = !Args.hasArg(OPT_dM);
3618   else
3619     Opts.ShowCPP = 0;
3620 
3621   Opts.ShowComments = Args.hasArg(OPT_C);
3622   Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
3623   Opts.ShowMacroComments = Args.hasArg(OPT_CC);
3624   Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
3625   Opts.ShowIncludeDirectives = Args.hasArg(OPT_dI);
3626   Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
3627   Opts.RewriteImports = Args.hasArg(OPT_frewrite_imports);
3628   Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
3629 }
3630 
3631 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
3632                             DiagnosticsEngine &Diags) {
3633   Opts.CodeModel = std::string(Args.getLastArgValue(OPT_mcmodel_EQ, "default"));
3634   Opts.ABI = std::string(Args.getLastArgValue(OPT_target_abi));
3635   if (Arg *A = Args.getLastArg(OPT_meabi)) {
3636     StringRef Value = A->getValue();
3637     llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value)
3638                                  .Case("default", llvm::EABI::Default)
3639                                  .Case("4", llvm::EABI::EABI4)
3640                                  .Case("5", llvm::EABI::EABI5)
3641                                  .Case("gnu", llvm::EABI::GNU)
3642                                  .Default(llvm::EABI::Unknown);
3643     if (EABIVersion == llvm::EABI::Unknown)
3644       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
3645                                                 << Value;
3646     else
3647       Opts.EABIVersion = EABIVersion;
3648   }
3649   Opts.CPU = std::string(Args.getLastArgValue(OPT_target_cpu));
3650   Opts.FPMath = std::string(Args.getLastArgValue(OPT_mfpmath));
3651   Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
3652   Opts.LinkerVersion =
3653       std::string(Args.getLastArgValue(OPT_target_linker_version));
3654   Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
3655   Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128);
3656   Opts.NVPTXUseShortPointers = Args.hasFlag(
3657       options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false);
3658   if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
3659     llvm::VersionTuple Version;
3660     if (Version.tryParse(A->getValue()))
3661       Diags.Report(diag::err_drv_invalid_value)
3662           << A->getAsString(Args) << A->getValue();
3663     else
3664       Opts.SDKVersion = Version;
3665   }
3666 }
3667 
3668 bool CompilerInvocation::parseSimpleArgs(const ArgList &Args,
3669                                          DiagnosticsEngine &Diags) {
3670 #define OPTION_WITH_MARSHALLING_FLAG(PREFIX_TYPE, NAME, ID, KIND, GROUP,       \
3671                                      ALIAS, ALIASARGS, FLAGS, PARAM, HELPTEXT, \
3672                                      METAVAR, VALUES, SPELLING, ALWAYS_EMIT,   \
3673                                      KEYPATH, DEFAULT_VALUE, IS_POSITIVE)      \
3674   this->KEYPATH = Args.hasArg(OPT_##ID) && IS_POSITIVE;
3675 
3676 #define OPTION_WITH_MARSHALLING_STRING(                                        \
3677     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
3678     HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,  \
3679     TYPE, NORMALIZER, DENORMALIZER, TABLE_INDEX)                               \
3680   {                                                                            \
3681     if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, Args, Diags))      \
3682       this->KEYPATH = static_cast<TYPE>(*MaybeValue);                          \
3683     else                                                                       \
3684       this->KEYPATH = DEFAULT_VALUE;                                           \
3685   }
3686 
3687 #include "clang/Driver/Options.inc"
3688 #undef OPTION_WITH_MARSHALLING_STRING
3689 #undef OPTION_WITH_MARSHALLING_FLAG
3690   return true;
3691 }
3692 
3693 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
3694                                         ArrayRef<const char *> CommandLineArgs,
3695                                         DiagnosticsEngine &Diags,
3696                                         const char *Argv0) {
3697   bool Success = true;
3698 
3699   // Parse the arguments.
3700   const OptTable &Opts = getDriverOptTable();
3701   const unsigned IncludedFlagsBitmask = options::CC1Option;
3702   unsigned MissingArgIndex, MissingArgCount;
3703   InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
3704                                      MissingArgCount, IncludedFlagsBitmask);
3705   LangOptions &LangOpts = *Res.getLangOpts();
3706 
3707   // Check for missing argument error.
3708   if (MissingArgCount) {
3709     Diags.Report(diag::err_drv_missing_argument)
3710         << Args.getArgString(MissingArgIndex) << MissingArgCount;
3711     Success = false;
3712   }
3713 
3714   // Issue errors on unknown arguments.
3715   for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
3716     auto ArgString = A->getAsString(Args);
3717     std::string Nearest;
3718     if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
3719       Diags.Report(diag::err_drv_unknown_argument) << ArgString;
3720     else
3721       Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
3722           << ArgString << Nearest;
3723     Success = false;
3724   }
3725 
3726   Success &= Res.parseSimpleArgs(Args, Diags);
3727 
3728   llvm::sys::Process::UseANSIEscapeCodes(
3729       Res.DiagnosticOpts->UseANSIEscapeCodes);
3730 
3731   Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
3732   Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args);
3733   ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args);
3734   if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
3735       Res.getDependencyOutputOpts().Targets.empty()) {
3736     Diags.Report(diag::err_fe_dependency_file_requires_MT);
3737     Success = false;
3738   }
3739   Success &= ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
3740                                  /*DefaultDiagColor=*/false);
3741   ParseCommentArgs(LangOpts.CommentOpts, Args);
3742   ParseFileSystemArgs(Res.getFileSystemOpts(), Args);
3743   // FIXME: We shouldn't have to pass the DashX option around here
3744   InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
3745                                       LangOpts.IsHeaderFile);
3746   ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
3747   Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags,
3748                               Res.getTargetOpts(), Res.getFrontendOpts());
3749   ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args,
3750                         Res.getFileSystemOpts().WorkingDir);
3751   llvm::Triple T(Res.getTargetOpts().Triple);
3752   if (DashX.getFormat() == InputKind::Precompiled ||
3753       DashX.getLanguage() == Language::LLVM_IR) {
3754     // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3755     // PassManager in BackendUtil.cpp. They need to be initializd no matter
3756     // what the input type is.
3757     if (Args.hasArg(OPT_fobjc_arc))
3758       LangOpts.ObjCAutoRefCount = 1;
3759     // PIClevel and PIELevel are needed during code generation and this should be
3760     // set regardless of the input type.
3761     LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3762     LangOpts.PIE = Args.hasArg(OPT_pic_is_pie);
3763     parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3764                         Diags, LangOpts.Sanitize);
3765   } else {
3766     // Other LangOpts are only initialized when the input is not AST or LLVM IR.
3767     // FIXME: Should we really be calling this for an Language::Asm input?
3768     ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(),
3769                   Res.getPreprocessorOpts(), Diags);
3770     if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
3771       LangOpts.ObjCExceptions = 1;
3772     if (T.isOSDarwin() && DashX.isPreprocessed()) {
3773       // Supress the darwin-specific 'stdlibcxx-not-found' diagnostic for
3774       // preprocessed input as we don't expect it to be used with -std=libc++
3775       // anyway.
3776       Res.getDiagnosticOpts().Warnings.push_back("no-stdlibcxx-not-found");
3777     }
3778   }
3779 
3780   if (Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation()))
3781     Res.FrontendOpts.LLVMArgs.push_back("-pgo-warn-misexpect");
3782 
3783   LangOpts.FunctionAlignment =
3784       getLastArgIntValue(Args, OPT_function_alignment, 0, Diags);
3785 
3786   if (LangOpts.CUDA) {
3787     // During CUDA device-side compilation, the aux triple is the
3788     // triple used for host compilation.
3789     if (LangOpts.CUDAIsDevice)
3790       Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
3791   }
3792 
3793   // Set the triple of the host for OpenMP device compile.
3794   if (LangOpts.OpenMPIsDevice)
3795     Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
3796 
3797   // FIXME: Override value name discarding when asan or msan is used because the
3798   // backend passes depend on the name of the alloca in order to print out
3799   // names.
3800   Res.getCodeGenOpts().DiscardValueNames &=
3801       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3802       !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
3803       !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
3804       !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
3805 
3806   ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
3807                         Res.getFrontendOpts().ProgramAction);
3808   ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args,
3809                               Res.getFrontendOpts().ProgramAction);
3810 
3811   // Turn on -Wspir-compat for SPIR target.
3812   if (T.isSPIR())
3813     Res.getDiagnosticOpts().Warnings.push_back("spir-compat");
3814 
3815   // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
3816   if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
3817       !Res.getLangOpts()->Sanitize.empty()) {
3818     Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
3819     Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
3820   }
3821 
3822   // Store the command-line for using in the CodeView backend.
3823   Res.getCodeGenOpts().Argv0 = Argv0;
3824   Res.getCodeGenOpts().CommandLineArgs = CommandLineArgs;
3825 
3826   return Success;
3827 }
3828 
3829 std::string CompilerInvocation::getModuleHash() const {
3830   // Note: For QoI reasons, the things we use as a hash here should all be
3831   // dumped via the -module-info flag.
3832   using llvm::hash_code;
3833   using llvm::hash_value;
3834   using llvm::hash_combine;
3835   using llvm::hash_combine_range;
3836 
3837   // Start the signature with the compiler version.
3838   // FIXME: We'd rather use something more cryptographically sound than
3839   // CityHash, but this will do for now.
3840   hash_code code = hash_value(getClangFullRepositoryVersion());
3841 
3842   // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
3843   // and getClangFullRepositoryVersion() doesn't include git revision.
3844   code = hash_combine(code, serialization::VERSION_MAJOR,
3845                       serialization::VERSION_MINOR);
3846 
3847   // Extend the signature with the language options
3848 #define LANGOPT(Name, Bits, Default, Description) \
3849    code = hash_combine(code, LangOpts->Name);
3850 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3851   code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
3852 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
3853 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
3854 #include "clang/Basic/LangOptions.def"
3855 
3856   for (StringRef Feature : LangOpts->ModuleFeatures)
3857     code = hash_combine(code, Feature);
3858 
3859   code = hash_combine(code, LangOpts->ObjCRuntime);
3860   const auto &BCN = LangOpts->CommentOpts.BlockCommandNames;
3861   code = hash_combine(code, hash_combine_range(BCN.begin(), BCN.end()));
3862 
3863   // Extend the signature with the target options.
3864   code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
3865                       TargetOpts->ABI);
3866   for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
3867     code = hash_combine(code, FeatureAsWritten);
3868 
3869   // Extend the signature with preprocessor options.
3870   const PreprocessorOptions &ppOpts = getPreprocessorOpts();
3871   const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
3872   code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
3873 
3874   for (const auto &I : getPreprocessorOpts().Macros) {
3875     // If we're supposed to ignore this macro for the purposes of modules,
3876     // don't put it into the hash.
3877     if (!hsOpts.ModulesIgnoreMacros.empty()) {
3878       // Check whether we're ignoring this macro.
3879       StringRef MacroDef = I.first;
3880       if (hsOpts.ModulesIgnoreMacros.count(
3881               llvm::CachedHashString(MacroDef.split('=').first)))
3882         continue;
3883     }
3884 
3885     code = hash_combine(code, I.first, I.second);
3886   }
3887 
3888   // Extend the signature with the sysroot and other header search options.
3889   code = hash_combine(code, hsOpts.Sysroot,
3890                       hsOpts.ModuleFormat,
3891                       hsOpts.UseDebugInfo,
3892                       hsOpts.UseBuiltinIncludes,
3893                       hsOpts.UseStandardSystemIncludes,
3894                       hsOpts.UseStandardCXXIncludes,
3895                       hsOpts.UseLibcxx,
3896                       hsOpts.ModulesValidateDiagnosticOptions);
3897   code = hash_combine(code, hsOpts.ResourceDir);
3898 
3899   if (hsOpts.ModulesStrictContextHash) {
3900     hash_code SHPC = hash_combine_range(hsOpts.SystemHeaderPrefixes.begin(),
3901                                         hsOpts.SystemHeaderPrefixes.end());
3902     hash_code UEC = hash_combine_range(hsOpts.UserEntries.begin(),
3903                                        hsOpts.UserEntries.end());
3904     code = hash_combine(code, hsOpts.SystemHeaderPrefixes.size(), SHPC,
3905                         hsOpts.UserEntries.size(), UEC);
3906 
3907     const DiagnosticOptions &diagOpts = getDiagnosticOpts();
3908     #define DIAGOPT(Name, Bits, Default) \
3909       code = hash_combine(code, diagOpts.Name);
3910     #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
3911       code = hash_combine(code, diagOpts.get##Name());
3912     #include "clang/Basic/DiagnosticOptions.def"
3913     #undef DIAGOPT
3914     #undef ENUM_DIAGOPT
3915   }
3916 
3917   // Extend the signature with the user build path.
3918   code = hash_combine(code, hsOpts.ModuleUserBuildPath);
3919 
3920   // Extend the signature with the module file extensions.
3921   const FrontendOptions &frontendOpts = getFrontendOpts();
3922   for (const auto &ext : frontendOpts.ModuleFileExtensions) {
3923     code = ext->hashExtension(code);
3924   }
3925 
3926   // When compiling with -gmodules, also hash -fdebug-prefix-map as it
3927   // affects the debug info in the PCM.
3928   if (getCodeGenOpts().DebugTypeExtRefs)
3929     for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap)
3930       code = hash_combine(code, KeyValue.first, KeyValue.second);
3931 
3932   // Extend the signature with the enabled sanitizers, if at least one is
3933   // enabled. Sanitizers which cannot affect AST generation aren't hashed.
3934   SanitizerSet SanHash = LangOpts->Sanitize;
3935   SanHash.clear(getPPTransparentSanitizers());
3936   if (!SanHash.empty())
3937     code = hash_combine(code, SanHash.Mask);
3938 
3939   return llvm::APInt(64, code).toString(36, /*Signed=*/false);
3940 }
3941 
3942 void CompilerInvocation::generateCC1CommandLine(
3943     SmallVectorImpl<const char *> &Args, StringAllocator SA) const {
3944 #define OPTION_WITH_MARSHALLING_FLAG(PREFIX_TYPE, NAME, ID, KIND, GROUP,       \
3945                                      ALIAS, ALIASARGS, FLAGS, PARAM, HELPTEXT, \
3946                                      METAVAR, VALUES, SPELLING, ALWAYS_EMIT,   \
3947                                      KEYPATH, DEFAULT_VALUE, IS_POSITIVE)      \
3948   if ((FLAGS) & options::CC1Option &&                                            \
3949       (ALWAYS_EMIT || this->KEYPATH != DEFAULT_VALUE))                         \
3950     Args.push_back(SPELLING);
3951 
3952 #define OPTION_WITH_MARSHALLING_STRING(                                        \
3953     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
3954     HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,  \
3955     NORMALIZER_RET_TY, NORMALIZER, DENORMALIZER, TABLE_INDEX)                  \
3956   if (((FLAGS) & options::CC1Option) &&                                          \
3957       (ALWAYS_EMIT || this->KEYPATH != DEFAULT_VALUE)) {                       \
3958     if (Option::KIND##Class == Option::SeparateClass) {                        \
3959       Args.push_back(SPELLING);                                                \
3960       Args.push_back(DENORMALIZER(SA, TABLE_INDEX, this->KEYPATH));            \
3961     }                                                                          \
3962   }
3963 
3964 #include "clang/Driver/Options.inc"
3965 #undef OPTION_WITH_MARSHALLING_STRING
3966 #undef OPTION_WITH_MARSHALLING_FLAG
3967 }
3968 
3969 namespace clang {
3970 
3971 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
3972 createVFSFromCompilerInvocation(const CompilerInvocation &CI,
3973                                 DiagnosticsEngine &Diags) {
3974   return createVFSFromCompilerInvocation(CI, Diags,
3975                                          llvm::vfs::getRealFileSystem());
3976 }
3977 
3978 IntrusiveRefCntPtr<llvm::vfs::FileSystem> createVFSFromCompilerInvocation(
3979     const CompilerInvocation &CI, DiagnosticsEngine &Diags,
3980     IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
3981   if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
3982     return BaseFS;
3983 
3984   IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
3985   // earlier vfs files are on the bottom
3986   for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
3987     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
3988         Result->getBufferForFile(File);
3989     if (!Buffer) {
3990       Diags.Report(diag::err_missing_vfs_overlay_file) << File;
3991       continue;
3992     }
3993 
3994     IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
3995         std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
3996         /*DiagContext*/ nullptr, Result);
3997     if (!FS) {
3998       Diags.Report(diag::err_invalid_vfs_overlay) << File;
3999       continue;
4000     }
4001 
4002     Result = FS;
4003   }
4004   return Result;
4005 }
4006 
4007 } // namespace clang
4008