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