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