xref: /llvm-project/clang/lib/Frontend/CompilerInvocation.cpp (revision a5bf4860eaee23c5bb7bd945516cd4d9f1873d5d)
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/Diagnostic.h"
16 #include "clang/Basic/DiagnosticDriver.h"
17 #include "clang/Basic/DiagnosticOptions.h"
18 #include "clang/Basic/FileSystemOptions.h"
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/LangStandard.h"
22 #include "clang/Basic/ObjCRuntime.h"
23 #include "clang/Basic/Sanitizers.h"
24 #include "clang/Basic/SourceLocation.h"
25 #include "clang/Basic/TargetOptions.h"
26 #include "clang/Basic/Version.h"
27 #include "clang/Basic/Visibility.h"
28 #include "clang/Basic/XRayInstr.h"
29 #include "clang/Config/config.h"
30 #include "clang/Driver/Driver.h"
31 #include "clang/Driver/DriverDiagnostic.h"
32 #include "clang/Driver/Options.h"
33 #include "clang/Frontend/CommandLineSourceLoc.h"
34 #include "clang/Frontend/DependencyOutputOptions.h"
35 #include "clang/Frontend/FrontendDiagnostic.h"
36 #include "clang/Frontend/FrontendOptions.h"
37 #include "clang/Frontend/FrontendPluginRegistry.h"
38 #include "clang/Frontend/MigratorOptions.h"
39 #include "clang/Frontend/PreprocessorOutputOptions.h"
40 #include "clang/Frontend/TextDiagnosticBuffer.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/DenseSet.h"
52 #include "llvm/ADT/FloatingPointMode.h"
53 #include "llvm/ADT/Hashing.h"
54 #include "llvm/ADT/STLExtras.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/Twine.h"
60 #include "llvm/Config/llvm-config.h"
61 #include "llvm/Frontend/Debug/Options.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/HashBuilder.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 "llvm/TargetParser/Host.h"
89 #include "llvm/TargetParser/Triple.h"
90 #include <algorithm>
91 #include <atomic>
92 #include <cassert>
93 #include <cstddef>
94 #include <cstring>
95 #include <ctime>
96 #include <fstream>
97 #include <limits>
98 #include <memory>
99 #include <optional>
100 #include <string>
101 #include <tuple>
102 #include <type_traits>
103 #include <utility>
104 #include <vector>
105 
106 using namespace clang;
107 using namespace driver;
108 using namespace options;
109 using namespace llvm::opt;
110 
111 //===----------------------------------------------------------------------===//
112 // Helpers.
113 //===----------------------------------------------------------------------===//
114 
115 // Parse misexpect tolerance argument value.
116 // Valid option values are integers in the range [0, 100)
117 static Expected<std::optional<uint32_t>> parseToleranceOption(StringRef Arg) {
118   uint32_t Val;
119   if (Arg.getAsInteger(10, Val))
120     return llvm::createStringError(llvm::inconvertibleErrorCode(),
121                                    "Not an integer: %s", Arg.data());
122   return Val;
123 }
124 
125 //===----------------------------------------------------------------------===//
126 // Initialization.
127 //===----------------------------------------------------------------------===//
128 
129 CompilerInvocationRefBase::CompilerInvocationRefBase()
130     : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
131       DiagnosticOpts(new DiagnosticOptions()),
132       HeaderSearchOpts(new HeaderSearchOptions()),
133       PreprocessorOpts(new PreprocessorOptions()),
134       AnalyzerOpts(new AnalyzerOptions()) {}
135 
136 CompilerInvocationRefBase::CompilerInvocationRefBase(
137     const CompilerInvocationRefBase &X)
138     : LangOpts(new LangOptions(*X.getLangOpts())),
139       TargetOpts(new TargetOptions(X.getTargetOpts())),
140       DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
141       HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
142       PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())),
143       AnalyzerOpts(new AnalyzerOptions(*X.getAnalyzerOpts())) {}
144 
145 CompilerInvocationRefBase::CompilerInvocationRefBase(
146     CompilerInvocationRefBase &&X) = default;
147 
148 CompilerInvocationRefBase &
149 CompilerInvocationRefBase::operator=(CompilerInvocationRefBase X) {
150   LangOpts.swap(X.LangOpts);
151   TargetOpts.swap(X.TargetOpts);
152   DiagnosticOpts.swap(X.DiagnosticOpts);
153   HeaderSearchOpts.swap(X.HeaderSearchOpts);
154   PreprocessorOpts.swap(X.PreprocessorOpts);
155   AnalyzerOpts.swap(X.AnalyzerOpts);
156   return *this;
157 }
158 
159 CompilerInvocationRefBase &
160 CompilerInvocationRefBase::operator=(CompilerInvocationRefBase &&X) = default;
161 
162 CompilerInvocationRefBase::~CompilerInvocationRefBase() = default;
163 
164 //===----------------------------------------------------------------------===//
165 // Normalizers
166 //===----------------------------------------------------------------------===//
167 
168 #define SIMPLE_ENUM_VALUE_TABLE
169 #include "clang/Driver/Options.inc"
170 #undef SIMPLE_ENUM_VALUE_TABLE
171 
172 static std::optional<bool> normalizeSimpleFlag(OptSpecifier Opt,
173                                                unsigned TableIndex,
174                                                const ArgList &Args,
175                                                DiagnosticsEngine &Diags) {
176   if (Args.hasArg(Opt))
177     return true;
178   return std::nullopt;
179 }
180 
181 static std::optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt,
182                                                        unsigned,
183                                                        const ArgList &Args,
184                                                        DiagnosticsEngine &) {
185   if (Args.hasArg(Opt))
186     return false;
187   return std::nullopt;
188 }
189 
190 /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
191 /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
192 /// unnecessary template instantiations and just ignore it with a variadic
193 /// argument.
194 static void denormalizeSimpleFlag(SmallVectorImpl<const char *> &Args,
195                                   const char *Spelling,
196                                   CompilerInvocation::StringAllocator,
197                                   Option::OptionClass, unsigned, /*T*/...) {
198   Args.push_back(Spelling);
199 }
200 
201 template <typename T> static constexpr bool is_uint64_t_convertible() {
202   return !std::is_same_v<T, uint64_t> && llvm::is_integral_or_enum<T>::value;
203 }
204 
205 template <typename T,
206           std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
207 static auto makeFlagToValueNormalizer(T Value) {
208   return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
209                  DiagnosticsEngine &) -> std::optional<T> {
210     if (Args.hasArg(Opt))
211       return Value;
212     return std::nullopt;
213   };
214 }
215 
216 template <typename T,
217           std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
218 static auto makeFlagToValueNormalizer(T Value) {
219   return makeFlagToValueNormalizer(uint64_t(Value));
220 }
221 
222 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
223                                         OptSpecifier OtherOpt) {
224   return [Value, OtherValue,
225           OtherOpt](OptSpecifier Opt, unsigned, const ArgList &Args,
226                     DiagnosticsEngine &) -> std::optional<bool> {
227     if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
228       return A->getOption().matches(Opt) ? Value : OtherValue;
229     }
230     return std::nullopt;
231   };
232 }
233 
234 static auto makeBooleanOptionDenormalizer(bool Value) {
235   return [Value](SmallVectorImpl<const char *> &Args, const char *Spelling,
236                  CompilerInvocation::StringAllocator, Option::OptionClass,
237                  unsigned, bool KeyPath) {
238     if (KeyPath == Value)
239       Args.push_back(Spelling);
240   };
241 }
242 
243 static void denormalizeStringImpl(SmallVectorImpl<const char *> &Args,
244                                   const char *Spelling,
245                                   CompilerInvocation::StringAllocator SA,
246                                   Option::OptionClass OptClass, unsigned,
247                                   const Twine &Value) {
248   switch (OptClass) {
249   case Option::SeparateClass:
250   case Option::JoinedOrSeparateClass:
251   case Option::JoinedAndSeparateClass:
252     Args.push_back(Spelling);
253     Args.push_back(SA(Value));
254     break;
255   case Option::JoinedClass:
256   case Option::CommaJoinedClass:
257     Args.push_back(SA(Twine(Spelling) + Value));
258     break;
259   default:
260     llvm_unreachable("Cannot denormalize an option with option class "
261                      "incompatible with string denormalization.");
262   }
263 }
264 
265 template <typename T>
266 static void
267 denormalizeString(SmallVectorImpl<const char *> &Args, const char *Spelling,
268                   CompilerInvocation::StringAllocator SA,
269                   Option::OptionClass OptClass, unsigned TableIndex, T Value) {
270   denormalizeStringImpl(Args, Spelling, SA, OptClass, TableIndex, Twine(Value));
271 }
272 
273 static std::optional<SimpleEnumValue>
274 findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
275   for (int I = 0, E = Table.Size; I != E; ++I)
276     if (Name == Table.Table[I].Name)
277       return Table.Table[I];
278 
279   return std::nullopt;
280 }
281 
282 static std::optional<SimpleEnumValue>
283 findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
284   for (int I = 0, E = Table.Size; I != E; ++I)
285     if (Value == Table.Table[I].Value)
286       return Table.Table[I];
287 
288   return std::nullopt;
289 }
290 
291 static std::optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt,
292                                                    unsigned TableIndex,
293                                                    const ArgList &Args,
294                                                    DiagnosticsEngine &Diags) {
295   assert(TableIndex < SimpleEnumValueTablesSize);
296   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
297 
298   auto *Arg = Args.getLastArg(Opt);
299   if (!Arg)
300     return std::nullopt;
301 
302   StringRef ArgValue = Arg->getValue();
303   if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
304     return MaybeEnumVal->Value;
305 
306   Diags.Report(diag::err_drv_invalid_value)
307       << Arg->getAsString(Args) << ArgValue;
308   return std::nullopt;
309 }
310 
311 static void denormalizeSimpleEnumImpl(SmallVectorImpl<const char *> &Args,
312                                       const char *Spelling,
313                                       CompilerInvocation::StringAllocator SA,
314                                       Option::OptionClass OptClass,
315                                       unsigned TableIndex, unsigned Value) {
316   assert(TableIndex < SimpleEnumValueTablesSize);
317   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
318   if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
319     denormalizeString(Args, Spelling, SA, OptClass, TableIndex,
320                       MaybeEnumVal->Name);
321   } else {
322     llvm_unreachable("The simple enum value was not correctly defined in "
323                      "the tablegen option description");
324   }
325 }
326 
327 template <typename T>
328 static void denormalizeSimpleEnum(SmallVectorImpl<const char *> &Args,
329                                   const char *Spelling,
330                                   CompilerInvocation::StringAllocator SA,
331                                   Option::OptionClass OptClass,
332                                   unsigned TableIndex, T Value) {
333   return denormalizeSimpleEnumImpl(Args, Spelling, SA, OptClass, TableIndex,
334                                    static_cast<unsigned>(Value));
335 }
336 
337 static std::optional<std::string> normalizeString(OptSpecifier Opt,
338                                                   int TableIndex,
339                                                   const ArgList &Args,
340                                                   DiagnosticsEngine &Diags) {
341   auto *Arg = Args.getLastArg(Opt);
342   if (!Arg)
343     return std::nullopt;
344   return std::string(Arg->getValue());
345 }
346 
347 template <typename IntTy>
348 static std::optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
349                                                     const ArgList &Args,
350                                                     DiagnosticsEngine &Diags) {
351   auto *Arg = Args.getLastArg(Opt);
352   if (!Arg)
353     return std::nullopt;
354   IntTy Res;
355   if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
356     Diags.Report(diag::err_drv_invalid_int_value)
357         << Arg->getAsString(Args) << Arg->getValue();
358     return std::nullopt;
359   }
360   return Res;
361 }
362 
363 static std::optional<std::vector<std::string>>
364 normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
365                       DiagnosticsEngine &) {
366   return Args.getAllArgValues(Opt);
367 }
368 
369 static void denormalizeStringVector(SmallVectorImpl<const char *> &Args,
370                                     const char *Spelling,
371                                     CompilerInvocation::StringAllocator SA,
372                                     Option::OptionClass OptClass,
373                                     unsigned TableIndex,
374                                     const std::vector<std::string> &Values) {
375   switch (OptClass) {
376   case Option::CommaJoinedClass: {
377     std::string CommaJoinedValue;
378     if (!Values.empty()) {
379       CommaJoinedValue.append(Values.front());
380       for (const std::string &Value : llvm::drop_begin(Values, 1)) {
381         CommaJoinedValue.append(",");
382         CommaJoinedValue.append(Value);
383       }
384     }
385     denormalizeString(Args, Spelling, SA, Option::OptionClass::JoinedClass,
386                       TableIndex, CommaJoinedValue);
387     break;
388   }
389   case Option::JoinedClass:
390   case Option::SeparateClass:
391   case Option::JoinedOrSeparateClass:
392     for (const std::string &Value : Values)
393       denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
394     break;
395   default:
396     llvm_unreachable("Cannot denormalize an option with option class "
397                      "incompatible with string vector denormalization.");
398   }
399 }
400 
401 static std::optional<std::string> normalizeTriple(OptSpecifier Opt,
402                                                   int TableIndex,
403                                                   const ArgList &Args,
404                                                   DiagnosticsEngine &Diags) {
405   auto *Arg = Args.getLastArg(Opt);
406   if (!Arg)
407     return std::nullopt;
408   return llvm::Triple::normalize(Arg->getValue());
409 }
410 
411 template <typename T, typename U>
412 static T mergeForwardValue(T KeyPath, U Value) {
413   return static_cast<T>(Value);
414 }
415 
416 template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
417   return KeyPath | Value;
418 }
419 
420 template <typename T> static T extractForwardValue(T KeyPath) {
421   return KeyPath;
422 }
423 
424 template <typename T, typename U, U Value>
425 static T extractMaskValue(T KeyPath) {
426   return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T();
427 }
428 
429 #define PARSE_OPTION_WITH_MARSHALLING(                                         \
430     ARGS, DIAGS, PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS,  \
431     PARAM, HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT,     \
432     KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,          \
433     DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX)                              \
434   if ((FLAGS)&options::CC1Option) {                                            \
435     KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE);                                  \
436     if (IMPLIED_CHECK)                                                         \
437       KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE);                                \
438     if (SHOULD_PARSE)                                                          \
439       if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS))    \
440         KEYPATH =                                                              \
441             MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue));      \
442   }
443 
444 // Capture the extracted value as a lambda argument to avoid potential issues
445 // with lifetime extension of the reference.
446 #define GENERATE_OPTION_WITH_MARSHALLING(                                      \
447     ARGS, STRING_ALLOCATOR, PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS,         \
448     ALIASARGS, FLAGS, PARAM, HELPTEXT, METAVAR, VALUES, SPELLING,              \
449     SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK,          \
450     IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX)   \
451   if ((FLAGS)&options::CC1Option) {                                            \
452     [&](const auto &Extracted) {                                               \
453       if (ALWAYS_EMIT ||                                                       \
454           (Extracted !=                                                        \
455            static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE)    \
456                                                           : (DEFAULT_VALUE)))) \
457         DENORMALIZER(ARGS, SPELLING, STRING_ALLOCATOR, Option::KIND##Class,    \
458                      TABLE_INDEX, Extracted);                                  \
459     }(EXTRACTOR(KEYPATH));                                                     \
460   }
461 
462 static StringRef GetInputKindName(InputKind IK);
463 
464 static bool FixupInvocation(CompilerInvocation &Invocation,
465                             DiagnosticsEngine &Diags, const ArgList &Args,
466                             InputKind IK) {
467   unsigned NumErrorsBefore = Diags.getNumErrors();
468 
469   LangOptions &LangOpts = *Invocation.getLangOpts();
470   CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
471   TargetOptions &TargetOpts = Invocation.getTargetOpts();
472   FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
473   CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
474   CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
475   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
476   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
477   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
478   if (FrontendOpts.ShowStats)
479     CodeGenOpts.ClearASTBeforeBackend = false;
480   LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
481   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
482   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
483   LangOpts.CurrentModule = LangOpts.ModuleName;
484 
485   llvm::Triple T(TargetOpts.Triple);
486   llvm::Triple::ArchType Arch = T.getArch();
487 
488   CodeGenOpts.CodeModel = TargetOpts.CodeModel;
489 
490   if (LangOpts.getExceptionHandling() !=
491           LangOptions::ExceptionHandlingKind::None &&
492       T.isWindowsMSVCEnvironment())
493     Diags.Report(diag::err_fe_invalid_exception_model)
494         << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
495 
496   if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
497     Diags.Report(diag::warn_c_kext);
498 
499   if (LangOpts.NewAlignOverride &&
500       !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
501     Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
502     Diags.Report(diag::err_fe_invalid_alignment)
503         << A->getAsString(Args) << A->getValue();
504     LangOpts.NewAlignOverride = 0;
505   }
506 
507   // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
508   if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
509     Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
510                                                           << "-fsycl-is-host";
511 
512   if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
513     Diags.Report(diag::err_drv_argument_not_allowed_with)
514         << "-fgnu89-inline" << GetInputKindName(IK);
515 
516   if (Args.hasArg(OPT_hlsl_entrypoint) && !LangOpts.HLSL)
517     Diags.Report(diag::err_drv_argument_not_allowed_with)
518         << "-hlsl-entry" << GetInputKindName(IK);
519 
520   if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
521     Diags.Report(diag::warn_ignored_hip_only_option)
522         << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
523 
524   if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
525     Diags.Report(diag::warn_ignored_hip_only_option)
526         << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
527 
528   // When these options are used, the compiler is allowed to apply
529   // optimizations that may affect the final result. For example
530   // (x+y)+z is transformed to x+(y+z) but may not give the same
531   // final result; it's not value safe.
532   // Another example can be to simplify x/x to 1.0 but x could be 0.0, INF
533   // or NaN. Final result may then differ. An error is issued when the eval
534   // method is set with one of these options.
535   if (Args.hasArg(OPT_ffp_eval_method_EQ)) {
536     if (LangOpts.ApproxFunc)
537       Diags.Report(diag::err_incompatible_fp_eval_method_options) << 0;
538     if (LangOpts.AllowFPReassoc)
539       Diags.Report(diag::err_incompatible_fp_eval_method_options) << 1;
540     if (LangOpts.AllowRecip)
541       Diags.Report(diag::err_incompatible_fp_eval_method_options) << 2;
542   }
543 
544   // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
545   // This option should be deprecated for CL > 1.0 because
546   // this option was added for compatibility with OpenCL 1.0.
547   if (Args.getLastArg(OPT_cl_strict_aliasing) &&
548       (LangOpts.getOpenCLCompatibleVersion() > 100))
549     Diags.Report(diag::warn_option_invalid_ocl_version)
550         << LangOpts.getOpenCLVersionString()
551         << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
552 
553   if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
554     auto DefaultCC = LangOpts.getDefaultCallingConv();
555 
556     bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
557                       DefaultCC == LangOptions::DCC_StdCall) &&
558                      Arch != llvm::Triple::x86;
559     emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
560                   DefaultCC == LangOptions::DCC_RegCall) &&
561                  !T.isX86();
562     if (emitError)
563       Diags.Report(diag::err_drv_argument_not_allowed_with)
564           << A->getSpelling() << T.getTriple();
565   }
566 
567   return Diags.getNumErrors() == NumErrorsBefore;
568 }
569 
570 //===----------------------------------------------------------------------===//
571 // Deserialization (from args)
572 //===----------------------------------------------------------------------===//
573 
574 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
575                                      DiagnosticsEngine &Diags) {
576   unsigned DefaultOpt = llvm::CodeGenOpt::None;
577   if ((IK.getLanguage() == Language::OpenCL ||
578        IK.getLanguage() == Language::OpenCLCXX) &&
579       !Args.hasArg(OPT_cl_opt_disable))
580     DefaultOpt = llvm::CodeGenOpt::Default;
581 
582   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
583     if (A->getOption().matches(options::OPT_O0))
584       return llvm::CodeGenOpt::None;
585 
586     if (A->getOption().matches(options::OPT_Ofast))
587       return llvm::CodeGenOpt::Aggressive;
588 
589     assert(A->getOption().matches(options::OPT_O));
590 
591     StringRef S(A->getValue());
592     if (S == "s" || S == "z")
593       return llvm::CodeGenOpt::Default;
594 
595     if (S == "g")
596       return llvm::CodeGenOpt::Less;
597 
598     return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
599   }
600 
601   return DefaultOpt;
602 }
603 
604 static unsigned getOptimizationLevelSize(ArgList &Args) {
605   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
606     if (A->getOption().matches(options::OPT_O)) {
607       switch (A->getValue()[0]) {
608       default:
609         return 0;
610       case 's':
611         return 1;
612       case 'z':
613         return 2;
614       }
615     }
616   }
617   return 0;
618 }
619 
620 static void GenerateArg(SmallVectorImpl<const char *> &Args,
621                         llvm::opt::OptSpecifier OptSpecifier,
622                         CompilerInvocation::StringAllocator SA) {
623   Option Opt = getDriverOptTable().getOption(OptSpecifier);
624   denormalizeSimpleFlag(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
625                         Option::OptionClass::FlagClass, 0);
626 }
627 
628 static void GenerateArg(SmallVectorImpl<const char *> &Args,
629                         llvm::opt::OptSpecifier OptSpecifier,
630                         const Twine &Value,
631                         CompilerInvocation::StringAllocator SA) {
632   Option Opt = getDriverOptTable().getOption(OptSpecifier);
633   denormalizeString(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
634                     Opt.getKind(), 0, Value);
635 }
636 
637 // Parse command line arguments into CompilerInvocation.
638 using ParseFn =
639     llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
640                             DiagnosticsEngine &, const char *)>;
641 
642 // Generate command line arguments from CompilerInvocation.
643 using GenerateFn = llvm::function_ref<void(
644     CompilerInvocation &, SmallVectorImpl<const char *> &,
645     CompilerInvocation::StringAllocator)>;
646 
647 /// May perform round-trip of command line arguments. By default, the round-trip
648 /// is enabled in assert builds. This can be overwritten at run-time via the
649 /// "-round-trip-args" and "-no-round-trip-args" command line flags, or via the
650 /// ForceRoundTrip parameter.
651 ///
652 /// During round-trip, the command line arguments are parsed into a dummy
653 /// CompilerInvocation, which is used to generate the command line arguments
654 /// again. The real CompilerInvocation is then created by parsing the generated
655 /// arguments, not the original ones. This (in combination with tests covering
656 /// argument behavior) ensures the generated command line is complete (doesn't
657 /// drop/mangle any arguments).
658 ///
659 /// Finally, we check the command line that was used to create the real
660 /// CompilerInvocation instance. By default, we compare it to the command line
661 /// the real CompilerInvocation generates. This checks whether the generator is
662 /// deterministic. If \p CheckAgainstOriginalInvocation is enabled, we instead
663 /// compare it to the original command line to verify the original command-line
664 /// was canonical and can round-trip exactly.
665 static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
666                       CompilerInvocation &RealInvocation,
667                       CompilerInvocation &DummyInvocation,
668                       ArrayRef<const char *> CommandLineArgs,
669                       DiagnosticsEngine &Diags, const char *Argv0,
670                       bool CheckAgainstOriginalInvocation = false,
671                       bool ForceRoundTrip = false) {
672 #ifndef NDEBUG
673   bool DoRoundTripDefault = true;
674 #else
675   bool DoRoundTripDefault = false;
676 #endif
677 
678   bool DoRoundTrip = DoRoundTripDefault;
679   if (ForceRoundTrip) {
680     DoRoundTrip = true;
681   } else {
682     for (const auto *Arg : CommandLineArgs) {
683       if (Arg == StringRef("-round-trip-args"))
684         DoRoundTrip = true;
685       if (Arg == StringRef("-no-round-trip-args"))
686         DoRoundTrip = false;
687     }
688   }
689 
690   // If round-trip was not requested, simply run the parser with the real
691   // invocation diagnostics.
692   if (!DoRoundTrip)
693     return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
694 
695   // Serializes quoted (and potentially escaped) arguments.
696   auto SerializeArgs = [](ArrayRef<const char *> Args) {
697     std::string Buffer;
698     llvm::raw_string_ostream OS(Buffer);
699     for (const char *Arg : Args) {
700       llvm::sys::printArg(OS, Arg, /*Quote=*/true);
701       OS << ' ';
702     }
703     OS.flush();
704     return Buffer;
705   };
706 
707   // Setup a dummy DiagnosticsEngine.
708   DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
709   DummyDiags.setClient(new TextDiagnosticBuffer());
710 
711   // Run the first parse on the original arguments with the dummy invocation and
712   // diagnostics.
713   if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
714       DummyDiags.getNumWarnings() != 0) {
715     // If the first parse did not succeed, it must be user mistake (invalid
716     // command line arguments). We won't be able to generate arguments that
717     // would reproduce the same result. Let's fail again with the real
718     // invocation and diagnostics, so all side-effects of parsing are visible.
719     unsigned NumWarningsBefore = Diags.getNumWarnings();
720     auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
721     if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
722       return Success;
723 
724     // Parse with original options and diagnostics succeeded even though it
725     // shouldn't have. Something is off.
726     Diags.Report(diag::err_cc1_round_trip_fail_then_ok);
727     Diags.Report(diag::note_cc1_round_trip_original)
728         << SerializeArgs(CommandLineArgs);
729     return false;
730   }
731 
732   // Setup string allocator.
733   llvm::BumpPtrAllocator Alloc;
734   llvm::StringSaver StringPool(Alloc);
735   auto SA = [&StringPool](const Twine &Arg) {
736     return StringPool.save(Arg).data();
737   };
738 
739   // Generate arguments from the dummy invocation. If Generate is the
740   // inverse of Parse, the newly generated arguments must have the same
741   // semantics as the original.
742   SmallVector<const char *> GeneratedArgs;
743   Generate(DummyInvocation, GeneratedArgs, SA);
744 
745   // Run the second parse, now on the generated arguments, and with the real
746   // invocation and diagnostics. The result is what we will end up using for the
747   // rest of compilation, so if Generate is not inverse of Parse, something down
748   // the line will break.
749   bool Success2 = Parse(RealInvocation, GeneratedArgs, Diags, Argv0);
750 
751   // The first parse on original arguments succeeded, but second parse of
752   // generated arguments failed. Something must be wrong with the generator.
753   if (!Success2) {
754     Diags.Report(diag::err_cc1_round_trip_ok_then_fail);
755     Diags.Report(diag::note_cc1_round_trip_generated)
756         << 1 << SerializeArgs(GeneratedArgs);
757     return false;
758   }
759 
760   SmallVector<const char *> ComparisonArgs;
761   if (CheckAgainstOriginalInvocation)
762     // Compare against original arguments.
763     ComparisonArgs.assign(CommandLineArgs.begin(), CommandLineArgs.end());
764   else
765     // Generate arguments again, this time from the options we will end up using
766     // for the rest of the compilation.
767     Generate(RealInvocation, ComparisonArgs, SA);
768 
769   // Compares two lists of arguments.
770   auto Equal = [](const ArrayRef<const char *> A,
771                   const ArrayRef<const char *> B) {
772     return std::equal(A.begin(), A.end(), B.begin(), B.end(),
773                       [](const char *AElem, const char *BElem) {
774                         return StringRef(AElem) == StringRef(BElem);
775                       });
776   };
777 
778   // If we generated different arguments from what we assume are two
779   // semantically equivalent CompilerInvocations, the Generate function may
780   // be non-deterministic.
781   if (!Equal(GeneratedArgs, ComparisonArgs)) {
782     Diags.Report(diag::err_cc1_round_trip_mismatch);
783     Diags.Report(diag::note_cc1_round_trip_generated)
784         << 1 << SerializeArgs(GeneratedArgs);
785     Diags.Report(diag::note_cc1_round_trip_generated)
786         << 2 << SerializeArgs(ComparisonArgs);
787     return false;
788   }
789 
790   Diags.Report(diag::remark_cc1_round_trip_generated)
791       << 1 << SerializeArgs(GeneratedArgs);
792   Diags.Report(diag::remark_cc1_round_trip_generated)
793       << 2 << SerializeArgs(ComparisonArgs);
794 
795   return Success2;
796 }
797 
798 bool CompilerInvocation::checkCC1RoundTrip(ArrayRef<const char *> Args,
799                                            DiagnosticsEngine &Diags,
800                                            const char *Argv0) {
801   CompilerInvocation DummyInvocation1, DummyInvocation2;
802   return RoundTrip(
803       [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
804          DiagnosticsEngine &Diags, const char *Argv0) {
805         return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
806       },
807       [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
808          StringAllocator SA) {
809         Args.push_back("-cc1");
810         Invocation.generateCC1CommandLine(Args, SA);
811       },
812       DummyInvocation1, DummyInvocation2, Args, Diags, Argv0,
813       /*CheckAgainstOriginalInvocation=*/true, /*ForceRoundTrip=*/true);
814 }
815 
816 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
817                               OptSpecifier GroupWithValue,
818                               std::vector<std::string> &Diagnostics) {
819   for (auto *A : Args.filtered(Group)) {
820     if (A->getOption().getKind() == Option::FlagClass) {
821       // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
822       // its name (minus the "W" or "R" at the beginning) to the diagnostics.
823       Diagnostics.push_back(
824           std::string(A->getOption().getName().drop_front(1)));
825     } else if (A->getOption().matches(GroupWithValue)) {
826       // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
827       // group. Add only the group name to the diagnostics.
828       Diagnostics.push_back(
829           std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
830     } else {
831       // Otherwise, add its value (for OPT_W_Joined and similar).
832       Diagnostics.push_back(A->getValue());
833     }
834   }
835 }
836 
837 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
838 // it won't verify the input.
839 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
840                                  DiagnosticsEngine *Diags);
841 
842 static void getAllNoBuiltinFuncValues(ArgList &Args,
843                                       std::vector<std::string> &Funcs) {
844   std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
845   auto BuiltinEnd = llvm::partition(Values, Builtin::Context::isBuiltinFunc);
846   Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
847 }
848 
849 static void GenerateAnalyzerArgs(AnalyzerOptions &Opts,
850                                  SmallVectorImpl<const char *> &Args,
851                                  CompilerInvocation::StringAllocator SA) {
852   const AnalyzerOptions *AnalyzerOpts = &Opts;
853 
854 #define ANALYZER_OPTION_WITH_MARSHALLING(...)                                  \
855   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
856 #include "clang/Driver/Options.inc"
857 #undef ANALYZER_OPTION_WITH_MARSHALLING
858 
859   if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
860     switch (Opts.AnalysisConstraintsOpt) {
861 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)                     \
862   case NAME##Model:                                                            \
863     GenerateArg(Args, OPT_analyzer_constraints, CMDFLAG, SA);                  \
864     break;
865 #include "clang/StaticAnalyzer/Core/Analyses.def"
866     default:
867       llvm_unreachable("Tried to generate unknown analysis constraint.");
868     }
869   }
870 
871   if (Opts.AnalysisDiagOpt != PD_HTML) {
872     switch (Opts.AnalysisDiagOpt) {
873 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN)                     \
874   case PD_##NAME:                                                              \
875     GenerateArg(Args, OPT_analyzer_output, CMDFLAG, SA);                       \
876     break;
877 #include "clang/StaticAnalyzer/Core/Analyses.def"
878     default:
879       llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
880     }
881   }
882 
883   if (Opts.AnalysisPurgeOpt != PurgeStmt) {
884     switch (Opts.AnalysisPurgeOpt) {
885 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC)                                    \
886   case NAME:                                                                   \
887     GenerateArg(Args, OPT_analyzer_purge, CMDFLAG, SA);                        \
888     break;
889 #include "clang/StaticAnalyzer/Core/Analyses.def"
890     default:
891       llvm_unreachable("Tried to generate unknown analysis purge mode.");
892     }
893   }
894 
895   if (Opts.InliningMode != NoRedundancy) {
896     switch (Opts.InliningMode) {
897 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC)                            \
898   case NAME:                                                                   \
899     GenerateArg(Args, OPT_analyzer_inlining_mode, CMDFLAG, SA);                \
900     break;
901 #include "clang/StaticAnalyzer/Core/Analyses.def"
902     default:
903       llvm_unreachable("Tried to generate unknown analysis inlining mode.");
904     }
905   }
906 
907   for (const auto &CP : Opts.CheckersAndPackages) {
908     OptSpecifier Opt =
909         CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
910     GenerateArg(Args, Opt, CP.first, SA);
911   }
912 
913   AnalyzerOptions ConfigOpts;
914   parseAnalyzerConfigs(ConfigOpts, nullptr);
915 
916   // Sort options by key to avoid relying on StringMap iteration order.
917   SmallVector<std::pair<StringRef, StringRef>, 4> SortedConfigOpts;
918   for (const auto &C : Opts.Config)
919     SortedConfigOpts.emplace_back(C.getKey(), C.getValue());
920   llvm::sort(SortedConfigOpts, llvm::less_first());
921 
922   for (const auto &[Key, Value] : SortedConfigOpts) {
923     // Don't generate anything that came from parseAnalyzerConfigs. It would be
924     // redundant and may not be valid on the command line.
925     auto Entry = ConfigOpts.Config.find(Key);
926     if (Entry != ConfigOpts.Config.end() && Entry->getValue() == Value)
927       continue;
928 
929     GenerateArg(Args, OPT_analyzer_config, Key + "=" + Value, SA);
930   }
931 
932   // Nothing to generate for FullCompilerInvocation.
933 }
934 
935 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
936                               DiagnosticsEngine &Diags) {
937   unsigned NumErrorsBefore = Diags.getNumErrors();
938 
939   AnalyzerOptions *AnalyzerOpts = &Opts;
940 
941 #define ANALYZER_OPTION_WITH_MARSHALLING(...)                                  \
942   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
943 #include "clang/Driver/Options.inc"
944 #undef ANALYZER_OPTION_WITH_MARSHALLING
945 
946   if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
947     StringRef Name = A->getValue();
948     AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
949 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
950       .Case(CMDFLAG, NAME##Model)
951 #include "clang/StaticAnalyzer/Core/Analyses.def"
952       .Default(NumConstraints);
953     if (Value == NumConstraints) {
954       Diags.Report(diag::err_drv_invalid_value)
955         << A->getAsString(Args) << Name;
956     } else {
957 #ifndef LLVM_WITH_Z3
958       if (Value == AnalysisConstraints::Z3ConstraintsModel) {
959         Diags.Report(diag::err_analyzer_not_built_with_z3);
960       }
961 #endif // LLVM_WITH_Z3
962       Opts.AnalysisConstraintsOpt = Value;
963     }
964   }
965 
966   if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
967     StringRef Name = A->getValue();
968     AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
969 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
970       .Case(CMDFLAG, PD_##NAME)
971 #include "clang/StaticAnalyzer/Core/Analyses.def"
972       .Default(NUM_ANALYSIS_DIAG_CLIENTS);
973     if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
974       Diags.Report(diag::err_drv_invalid_value)
975         << A->getAsString(Args) << Name;
976     } else {
977       Opts.AnalysisDiagOpt = Value;
978     }
979   }
980 
981   if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
982     StringRef Name = A->getValue();
983     AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
984 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
985       .Case(CMDFLAG, NAME)
986 #include "clang/StaticAnalyzer/Core/Analyses.def"
987       .Default(NumPurgeModes);
988     if (Value == NumPurgeModes) {
989       Diags.Report(diag::err_drv_invalid_value)
990         << A->getAsString(Args) << Name;
991     } else {
992       Opts.AnalysisPurgeOpt = Value;
993     }
994   }
995 
996   if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
997     StringRef Name = A->getValue();
998     AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
999 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
1000       .Case(CMDFLAG, NAME)
1001 #include "clang/StaticAnalyzer/Core/Analyses.def"
1002       .Default(NumInliningModes);
1003     if (Value == NumInliningModes) {
1004       Diags.Report(diag::err_drv_invalid_value)
1005         << A->getAsString(Args) << Name;
1006     } else {
1007       Opts.InliningMode = Value;
1008     }
1009   }
1010 
1011   Opts.CheckersAndPackages.clear();
1012   for (const Arg *A :
1013        Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
1014     A->claim();
1015     bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
1016     // We can have a list of comma separated checker names, e.g:
1017     // '-analyzer-checker=cocoa,unix'
1018     StringRef CheckerAndPackageList = A->getValue();
1019     SmallVector<StringRef, 16> CheckersAndPackages;
1020     CheckerAndPackageList.split(CheckersAndPackages, ",");
1021     for (const StringRef &CheckerOrPackage : CheckersAndPackages)
1022       Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
1023                                             IsEnabled);
1024   }
1025 
1026   // Go through the analyzer configuration options.
1027   for (const auto *A : Args.filtered(OPT_analyzer_config)) {
1028 
1029     // We can have a list of comma separated config names, e.g:
1030     // '-analyzer-config key1=val1,key2=val2'
1031     StringRef configList = A->getValue();
1032     SmallVector<StringRef, 4> configVals;
1033     configList.split(configVals, ",");
1034     for (const auto &configVal : configVals) {
1035       StringRef key, val;
1036       std::tie(key, val) = configVal.split("=");
1037       if (val.empty()) {
1038         Diags.Report(SourceLocation(),
1039                      diag::err_analyzer_config_no_value) << configVal;
1040         break;
1041       }
1042       if (val.contains('=')) {
1043         Diags.Report(SourceLocation(),
1044                      diag::err_analyzer_config_multiple_values)
1045           << configVal;
1046         break;
1047       }
1048 
1049       // TODO: Check checker options too, possibly in CheckerRegistry.
1050       // Leave unknown non-checker configs unclaimed.
1051       if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
1052         if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
1053           Diags.Report(diag::err_analyzer_config_unknown) << key;
1054         continue;
1055       }
1056 
1057       A->claim();
1058       Opts.Config[key] = std::string(val);
1059 
1060       // FIXME: Remove this hunk after clang-17 released.
1061       constexpr auto SingleFAM =
1062           "consider-single-element-arrays-as-flexible-array-members";
1063       if (key == SingleFAM) {
1064         Diags.Report(diag::warn_analyzer_deprecated_option_with_alternative)
1065             << SingleFAM << "clang-17"
1066             << "-fstrict-flex-arrays=<N>";
1067       }
1068     }
1069   }
1070 
1071   if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
1072     parseAnalyzerConfigs(Opts, &Diags);
1073   else
1074     parseAnalyzerConfigs(Opts, nullptr);
1075 
1076   llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
1077   for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
1078     if (i != 0)
1079       os << " ";
1080     os << Args.getArgString(i);
1081   }
1082   os.flush();
1083 
1084   return Diags.getNumErrors() == NumErrorsBefore;
1085 }
1086 
1087 static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
1088                                  StringRef OptionName, StringRef DefaultVal) {
1089   return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
1090 }
1091 
1092 static void initOption(AnalyzerOptions::ConfigTable &Config,
1093                        DiagnosticsEngine *Diags,
1094                        StringRef &OptionField, StringRef Name,
1095                        StringRef DefaultVal) {
1096   // String options may be known to invalid (e.g. if the expected string is a
1097   // file name, but the file does not exist), those will have to be checked in
1098   // parseConfigs.
1099   OptionField = getStringOption(Config, Name, DefaultVal);
1100 }
1101 
1102 static void initOption(AnalyzerOptions::ConfigTable &Config,
1103                        DiagnosticsEngine *Diags,
1104                        bool &OptionField, StringRef Name, bool DefaultVal) {
1105   auto PossiblyInvalidVal =
1106       llvm::StringSwitch<std::optional<bool>>(
1107           getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
1108           .Case("true", true)
1109           .Case("false", false)
1110           .Default(std::nullopt);
1111 
1112   if (!PossiblyInvalidVal) {
1113     if (Diags)
1114       Diags->Report(diag::err_analyzer_config_invalid_input)
1115         << Name << "a boolean";
1116     else
1117       OptionField = DefaultVal;
1118   } else
1119     OptionField = *PossiblyInvalidVal;
1120 }
1121 
1122 static void initOption(AnalyzerOptions::ConfigTable &Config,
1123                        DiagnosticsEngine *Diags,
1124                        unsigned &OptionField, StringRef Name,
1125                        unsigned DefaultVal) {
1126 
1127   OptionField = DefaultVal;
1128   bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
1129                      .getAsInteger(0, OptionField);
1130   if (Diags && HasFailed)
1131     Diags->Report(diag::err_analyzer_config_invalid_input)
1132       << Name << "an unsigned";
1133 }
1134 
1135 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
1136                                  DiagnosticsEngine *Diags) {
1137   // TODO: There's no need to store the entire configtable, it'd be plenty
1138   // enough to store checker options.
1139 
1140 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL)                \
1141   initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
1142 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(...)
1143 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1144 
1145   assert(AnOpts.UserMode == "shallow" || AnOpts.UserMode == "deep");
1146   const bool InShallowMode = AnOpts.UserMode == "shallow";
1147 
1148 #define ANALYZER_OPTION(...)
1149 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC,        \
1150                                              SHALLOW_VAL, DEEP_VAL)            \
1151   initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG,                       \
1152              InShallowMode ? SHALLOW_VAL : DEEP_VAL);
1153 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1154 
1155   // At this point, AnalyzerOptions is configured. Let's validate some options.
1156 
1157   // FIXME: Here we try to validate the silenced checkers or packages are valid.
1158   // The current approach only validates the registered checkers which does not
1159   // contain the runtime enabled checkers and optimally we would validate both.
1160   if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
1161     std::vector<StringRef> Checkers =
1162         AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
1163     std::vector<StringRef> Packages =
1164         AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
1165 
1166     SmallVector<StringRef, 16> CheckersAndPackages;
1167     AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
1168 
1169     for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
1170       if (Diags) {
1171         bool IsChecker = CheckerOrPackage.contains('.');
1172         bool IsValidName = IsChecker
1173                                ? llvm::is_contained(Checkers, CheckerOrPackage)
1174                                : llvm::is_contained(Packages, CheckerOrPackage);
1175 
1176         if (!IsValidName)
1177           Diags->Report(diag::err_unknown_analyzer_checker_or_package)
1178               << CheckerOrPackage;
1179       }
1180 
1181       AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
1182     }
1183   }
1184 
1185   if (!Diags)
1186     return;
1187 
1188   if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
1189     Diags->Report(diag::err_analyzer_config_invalid_input)
1190         << "track-conditions-debug" << "'track-conditions' to also be enabled";
1191 
1192   if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
1193     Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
1194                                                            << "a filename";
1195 
1196   if (!AnOpts.ModelPath.empty() &&
1197       !llvm::sys::fs::is_directory(AnOpts.ModelPath))
1198     Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
1199                                                            << "a filename";
1200 }
1201 
1202 /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
1203 static void
1204 GenerateOptimizationRemark(SmallVectorImpl<const char *> &Args,
1205                            CompilerInvocation::StringAllocator SA,
1206                            OptSpecifier OptEQ, StringRef Name,
1207                            const CodeGenOptions::OptRemark &Remark) {
1208   if (Remark.hasValidPattern()) {
1209     GenerateArg(Args, OptEQ, Remark.Pattern, SA);
1210   } else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
1211     GenerateArg(Args, OPT_R_Joined, Name, SA);
1212   } else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
1213     GenerateArg(Args, OPT_R_Joined, StringRef("no-") + Name, SA);
1214   }
1215 }
1216 
1217 /// Parse a remark command line argument. It may be missing, disabled/enabled by
1218 /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
1219 /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
1220 static CodeGenOptions::OptRemark
1221 ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args,
1222                         OptSpecifier OptEQ, StringRef Name) {
1223   CodeGenOptions::OptRemark Result;
1224 
1225   auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A,
1226                                                           StringRef Pattern) {
1227     Result.Pattern = Pattern.str();
1228 
1229     std::string RegexError;
1230     Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
1231     if (!Result.Regex->isValid(RegexError)) {
1232       Diags.Report(diag::err_drv_optimization_remark_pattern)
1233           << RegexError << A->getAsString(Args);
1234       return false;
1235     }
1236 
1237     return true;
1238   };
1239 
1240   for (Arg *A : Args) {
1241     if (A->getOption().matches(OPT_R_Joined)) {
1242       StringRef Value = A->getValue();
1243 
1244       if (Value == Name)
1245         Result.Kind = CodeGenOptions::RK_Enabled;
1246       else if (Value == "everything")
1247         Result.Kind = CodeGenOptions::RK_EnabledEverything;
1248       else if (Value.split('-') == std::make_pair(StringRef("no"), Name))
1249         Result.Kind = CodeGenOptions::RK_Disabled;
1250       else if (Value == "no-everything")
1251         Result.Kind = CodeGenOptions::RK_DisabledEverything;
1252       else
1253         continue;
1254 
1255       if (Result.Kind == CodeGenOptions::RK_Disabled ||
1256           Result.Kind == CodeGenOptions::RK_DisabledEverything) {
1257         Result.Pattern = "";
1258         Result.Regex = nullptr;
1259       } else {
1260         InitializeResultPattern(A, ".*");
1261       }
1262     } else if (A->getOption().matches(OptEQ)) {
1263       Result.Kind = CodeGenOptions::RK_WithPattern;
1264       if (!InitializeResultPattern(A, A->getValue()))
1265         return CodeGenOptions::OptRemark();
1266     }
1267   }
1268 
1269   return Result;
1270 }
1271 
1272 static bool parseDiagnosticLevelMask(StringRef FlagName,
1273                                      const std::vector<std::string> &Levels,
1274                                      DiagnosticsEngine &Diags,
1275                                      DiagnosticLevelMask &M) {
1276   bool Success = true;
1277   for (const auto &Level : Levels) {
1278     DiagnosticLevelMask const PM =
1279       llvm::StringSwitch<DiagnosticLevelMask>(Level)
1280         .Case("note",    DiagnosticLevelMask::Note)
1281         .Case("remark",  DiagnosticLevelMask::Remark)
1282         .Case("warning", DiagnosticLevelMask::Warning)
1283         .Case("error",   DiagnosticLevelMask::Error)
1284         .Default(DiagnosticLevelMask::None);
1285     if (PM == DiagnosticLevelMask::None) {
1286       Success = false;
1287       Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
1288     }
1289     M = M | PM;
1290   }
1291   return Success;
1292 }
1293 
1294 static void parseSanitizerKinds(StringRef FlagName,
1295                                 const std::vector<std::string> &Sanitizers,
1296                                 DiagnosticsEngine &Diags, SanitizerSet &S) {
1297   for (const auto &Sanitizer : Sanitizers) {
1298     SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
1299     if (K == SanitizerMask())
1300       Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
1301     else
1302       S.set(K, true);
1303   }
1304 }
1305 
1306 static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) {
1307   SmallVector<StringRef, 4> Values;
1308   serializeSanitizerSet(S, Values);
1309   return Values;
1310 }
1311 
1312 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
1313                                            ArgList &Args, DiagnosticsEngine &D,
1314                                            XRayInstrSet &S) {
1315   llvm::SmallVector<StringRef, 2> BundleParts;
1316   llvm::SplitString(Bundle, BundleParts, ",");
1317   for (const auto &B : BundleParts) {
1318     auto Mask = parseXRayInstrValue(B);
1319     if (Mask == XRayInstrKind::None)
1320       if (B != "none")
1321         D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
1322       else
1323         S.Mask = Mask;
1324     else if (Mask == XRayInstrKind::All)
1325       S.Mask = Mask;
1326     else
1327       S.set(Mask, true);
1328   }
1329 }
1330 
1331 static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
1332   llvm::SmallVector<StringRef, 2> BundleParts;
1333   serializeXRayInstrValue(S, BundleParts);
1334   std::string Buffer;
1335   llvm::raw_string_ostream OS(Buffer);
1336   llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
1337   return Buffer;
1338 }
1339 
1340 // Set the profile kind using fprofile-instrument-use-path.
1341 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
1342                                   const Twine &ProfileName,
1343                                   llvm::vfs::FileSystem &FS,
1344                                   DiagnosticsEngine &Diags) {
1345   auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName, FS);
1346   if (auto E = ReaderOrErr.takeError()) {
1347     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1348                                             "Error in reading profile %0: %1");
1349     llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
1350       Diags.Report(DiagID) << ProfileName.str() << EI.message();
1351     });
1352     return;
1353   }
1354   std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
1355     std::move(ReaderOrErr.get());
1356   // Currently memprof profiles are only added at the IR level. Mark the profile
1357   // type as IR in that case as well and the subsequent matching needs to detect
1358   // which is available (might be one or both).
1359   if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
1360     if (PGOReader->hasCSIRLevelProfile())
1361       Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
1362     else
1363       Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
1364   } else
1365     Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
1366 }
1367 
1368 void CompilerInvocation::GenerateCodeGenArgs(
1369     const CodeGenOptions &Opts, SmallVectorImpl<const char *> &Args,
1370     StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile,
1371     const LangOptions *LangOpts) {
1372   const CodeGenOptions &CodeGenOpts = Opts;
1373 
1374   if (Opts.OptimizationLevel == 0)
1375     GenerateArg(Args, OPT_O0, SA);
1376   else
1377     GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
1378 
1379 #define CODEGEN_OPTION_WITH_MARSHALLING(...)                                   \
1380   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
1381 #include "clang/Driver/Options.inc"
1382 #undef CODEGEN_OPTION_WITH_MARSHALLING
1383 
1384   if (Opts.OptimizationLevel > 0) {
1385     if (Opts.Inlining == CodeGenOptions::NormalInlining)
1386       GenerateArg(Args, OPT_finline_functions, SA);
1387     else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
1388       GenerateArg(Args, OPT_finline_hint_functions, SA);
1389     else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
1390       GenerateArg(Args, OPT_fno_inline, SA);
1391   }
1392 
1393   if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
1394     GenerateArg(Args, OPT_fdirect_access_external_data, SA);
1395   else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
1396     GenerateArg(Args, OPT_fno_direct_access_external_data, SA);
1397 
1398   std::optional<StringRef> DebugInfoVal;
1399   switch (Opts.DebugInfo) {
1400   case llvm::codegenoptions::DebugLineTablesOnly:
1401     DebugInfoVal = "line-tables-only";
1402     break;
1403   case llvm::codegenoptions::DebugDirectivesOnly:
1404     DebugInfoVal = "line-directives-only";
1405     break;
1406   case llvm::codegenoptions::DebugInfoConstructor:
1407     DebugInfoVal = "constructor";
1408     break;
1409   case llvm::codegenoptions::LimitedDebugInfo:
1410     DebugInfoVal = "limited";
1411     break;
1412   case llvm::codegenoptions::FullDebugInfo:
1413     DebugInfoVal = "standalone";
1414     break;
1415   case llvm::codegenoptions::UnusedTypeInfo:
1416     DebugInfoVal = "unused-types";
1417     break;
1418   case llvm::codegenoptions::NoDebugInfo: // default value
1419     DebugInfoVal = std::nullopt;
1420     break;
1421   case llvm::codegenoptions::LocTrackingOnly: // implied value
1422     DebugInfoVal = std::nullopt;
1423     break;
1424   }
1425   if (DebugInfoVal)
1426     GenerateArg(Args, OPT_debug_info_kind_EQ, *DebugInfoVal, SA);
1427 
1428   for (const auto &Prefix : Opts.DebugPrefixMap)
1429     GenerateArg(Args, OPT_fdebug_prefix_map_EQ,
1430                 Prefix.first + "=" + Prefix.second, SA);
1431 
1432   for (const auto &Prefix : Opts.CoveragePrefixMap)
1433     GenerateArg(Args, OPT_fcoverage_prefix_map_EQ,
1434                 Prefix.first + "=" + Prefix.second, SA);
1435 
1436   if (Opts.NewStructPathTBAA)
1437     GenerateArg(Args, OPT_new_struct_path_tbaa, SA);
1438 
1439   if (Opts.OptimizeSize == 1)
1440     GenerateArg(Args, OPT_O, "s", SA);
1441   else if (Opts.OptimizeSize == 2)
1442     GenerateArg(Args, OPT_O, "z", SA);
1443 
1444   // SimplifyLibCalls is set only in the absence of -fno-builtin and
1445   // -ffreestanding. We'll consider that when generating them.
1446 
1447   // NoBuiltinFuncs are generated by LangOptions.
1448 
1449   if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
1450     GenerateArg(Args, OPT_funroll_loops, SA);
1451   else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
1452     GenerateArg(Args, OPT_fno_unroll_loops, SA);
1453 
1454   if (!Opts.BinutilsVersion.empty())
1455     GenerateArg(Args, OPT_fbinutils_version_EQ, Opts.BinutilsVersion, SA);
1456 
1457   if (Opts.DebugNameTable ==
1458       static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
1459     GenerateArg(Args, OPT_ggnu_pubnames, SA);
1460   else if (Opts.DebugNameTable ==
1461            static_cast<unsigned>(
1462                llvm::DICompileUnit::DebugNameTableKind::Default))
1463     GenerateArg(Args, OPT_gpubnames, SA);
1464 
1465   auto TNK = Opts.getDebugSimpleTemplateNames();
1466   if (TNK != llvm::codegenoptions::DebugTemplateNamesKind::Full) {
1467     if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Simple)
1468       GenerateArg(Args, OPT_gsimple_template_names_EQ, "simple", SA);
1469     else if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Mangled)
1470       GenerateArg(Args, OPT_gsimple_template_names_EQ, "mangled", SA);
1471   }
1472   // ProfileInstrumentUsePath is marshalled automatically, no need to generate
1473   // it or PGOUseInstrumentor.
1474 
1475   if (Opts.TimePasses) {
1476     if (Opts.TimePassesPerRun)
1477       GenerateArg(Args, OPT_ftime_report_EQ, "per-pass-run", SA);
1478     else
1479       GenerateArg(Args, OPT_ftime_report, SA);
1480   }
1481 
1482   if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
1483     GenerateArg(Args, OPT_flto_EQ, "full", SA);
1484 
1485   if (Opts.PrepareForThinLTO)
1486     GenerateArg(Args, OPT_flto_EQ, "thin", SA);
1487 
1488   if (!Opts.ThinLTOIndexFile.empty())
1489     GenerateArg(Args, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile, SA);
1490 
1491   if (Opts.SaveTempsFilePrefix == OutputFile)
1492     GenerateArg(Args, OPT_save_temps_EQ, "obj", SA);
1493 
1494   StringRef MemProfileBasename("memprof.profraw");
1495   if (!Opts.MemoryProfileOutput.empty()) {
1496     if (Opts.MemoryProfileOutput == MemProfileBasename) {
1497       GenerateArg(Args, OPT_fmemory_profile, SA);
1498     } else {
1499       size_t ArgLength =
1500           Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
1501       GenerateArg(Args, OPT_fmemory_profile_EQ,
1502                   Opts.MemoryProfileOutput.substr(0, ArgLength), SA);
1503     }
1504   }
1505 
1506   if (memcmp(Opts.CoverageVersion, "408*", 4) != 0)
1507     GenerateArg(Args, OPT_coverage_version_EQ,
1508                 StringRef(Opts.CoverageVersion, 4), SA);
1509 
1510   // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
1511   //  '-fembed_bitcode', which does not map to any CompilerInvocation field and
1512   //  won't be generated.)
1513 
1514   if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) {
1515     std::string InstrBundle =
1516         serializeXRayInstrumentationBundle(Opts.XRayInstrumentationBundle);
1517     if (!InstrBundle.empty())
1518       GenerateArg(Args, OPT_fxray_instrumentation_bundle, InstrBundle, SA);
1519   }
1520 
1521   if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
1522     GenerateArg(Args, OPT_fcf_protection_EQ, "full", SA);
1523   else if (Opts.CFProtectionReturn)
1524     GenerateArg(Args, OPT_fcf_protection_EQ, "return", SA);
1525   else if (Opts.CFProtectionBranch)
1526     GenerateArg(Args, OPT_fcf_protection_EQ, "branch", SA);
1527 
1528   if (Opts.FunctionReturnThunks)
1529     GenerateArg(Args, OPT_mfunction_return_EQ, "thunk-extern", SA);
1530 
1531   for (const auto &F : Opts.LinkBitcodeFiles) {
1532     bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
1533                     F.PropagateAttrs && F.Internalize;
1534     GenerateArg(Args,
1535                 Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
1536                 F.Filename, SA);
1537   }
1538 
1539   if (Opts.EmulatedTLS)
1540     GenerateArg(Args, OPT_femulated_tls, SA);
1541 
1542   if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1543     GenerateArg(Args, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str(), SA);
1544 
1545   if ((Opts.FPDenormalMode != Opts.FP32DenormalMode) ||
1546       (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE()))
1547     GenerateArg(Args, OPT_fdenormal_fp_math_f32_EQ, Opts.FP32DenormalMode.str(),
1548                 SA);
1549 
1550   if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
1551     OptSpecifier Opt =
1552         T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
1553     GenerateArg(Args, Opt, SA);
1554   } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
1555     OptSpecifier Opt =
1556         T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
1557     GenerateArg(Args, Opt, SA);
1558   }
1559 
1560   if (Opts.EnableAIXExtendedAltivecABI)
1561     GenerateArg(Args, OPT_mabi_EQ_vec_extabi, SA);
1562 
1563   if (Opts.XCOFFReadOnlyPointers)
1564     GenerateArg(Args, OPT_mxcoff_roptr, SA);
1565 
1566   if (!Opts.OptRecordPasses.empty())
1567     GenerateArg(Args, OPT_opt_record_passes, Opts.OptRecordPasses, SA);
1568 
1569   if (!Opts.OptRecordFormat.empty())
1570     GenerateArg(Args, OPT_opt_record_format, Opts.OptRecordFormat, SA);
1571 
1572   GenerateOptimizationRemark(Args, SA, OPT_Rpass_EQ, "pass",
1573                              Opts.OptimizationRemark);
1574 
1575   GenerateOptimizationRemark(Args, SA, OPT_Rpass_missed_EQ, "pass-missed",
1576                              Opts.OptimizationRemarkMissed);
1577 
1578   GenerateOptimizationRemark(Args, SA, OPT_Rpass_analysis_EQ, "pass-analysis",
1579                              Opts.OptimizationRemarkAnalysis);
1580 
1581   GenerateArg(Args, OPT_fdiagnostics_hotness_threshold_EQ,
1582               Opts.DiagnosticsHotnessThreshold
1583                   ? Twine(*Opts.DiagnosticsHotnessThreshold)
1584                   : "auto",
1585               SA);
1586 
1587   GenerateArg(Args, OPT_fdiagnostics_misexpect_tolerance_EQ,
1588               Twine(*Opts.DiagnosticsMisExpectTolerance), SA);
1589 
1590   for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover))
1591     GenerateArg(Args, OPT_fsanitize_recover_EQ, Sanitizer, SA);
1592 
1593   for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap))
1594     GenerateArg(Args, OPT_fsanitize_trap_EQ, Sanitizer, SA);
1595 
1596   if (!Opts.EmitVersionIdentMetadata)
1597     GenerateArg(Args, OPT_Qn, SA);
1598 
1599   switch (Opts.FiniteLoops) {
1600   case CodeGenOptions::FiniteLoopsKind::Language:
1601     break;
1602   case CodeGenOptions::FiniteLoopsKind::Always:
1603     GenerateArg(Args, OPT_ffinite_loops, SA);
1604     break;
1605   case CodeGenOptions::FiniteLoopsKind::Never:
1606     GenerateArg(Args, OPT_fno_finite_loops, SA);
1607     break;
1608   }
1609 }
1610 
1611 bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
1612                                           InputKind IK,
1613                                           DiagnosticsEngine &Diags,
1614                                           const llvm::Triple &T,
1615                                           const std::string &OutputFile,
1616                                           const LangOptions &LangOptsRef) {
1617   unsigned NumErrorsBefore = Diags.getNumErrors();
1618 
1619   unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
1620   // TODO: This could be done in Driver
1621   unsigned MaxOptLevel = 3;
1622   if (OptimizationLevel > MaxOptLevel) {
1623     // If the optimization level is not supported, fall back on the default
1624     // optimization
1625     Diags.Report(diag::warn_drv_optimization_value)
1626         << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
1627     OptimizationLevel = MaxOptLevel;
1628   }
1629   Opts.OptimizationLevel = OptimizationLevel;
1630 
1631   // The key paths of codegen options defined in Options.td start with
1632   // "CodeGenOpts.". Let's provide the expected variable name and type.
1633   CodeGenOptions &CodeGenOpts = Opts;
1634   // Some codegen options depend on language options. Let's provide the expected
1635   // variable name and type.
1636   const LangOptions *LangOpts = &LangOptsRef;
1637 
1638 #define CODEGEN_OPTION_WITH_MARSHALLING(...)                                   \
1639   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1640 #include "clang/Driver/Options.inc"
1641 #undef CODEGEN_OPTION_WITH_MARSHALLING
1642 
1643   // At O0 we want to fully disable inlining outside of cases marked with
1644   // 'alwaysinline' that are required for correctness.
1645   if (Opts.OptimizationLevel == 0) {
1646     Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1647   } else if (const Arg *A = Args.getLastArg(options::OPT_finline_functions,
1648                                             options::OPT_finline_hint_functions,
1649                                             options::OPT_fno_inline_functions,
1650                                             options::OPT_fno_inline)) {
1651     // Explicit inlining flags can disable some or all inlining even at
1652     // optimization levels above zero.
1653     if (A->getOption().matches(options::OPT_finline_functions))
1654       Opts.setInlining(CodeGenOptions::NormalInlining);
1655     else if (A->getOption().matches(options::OPT_finline_hint_functions))
1656       Opts.setInlining(CodeGenOptions::OnlyHintInlining);
1657     else
1658       Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1659   } else {
1660     Opts.setInlining(CodeGenOptions::NormalInlining);
1661   }
1662 
1663   // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
1664   // -fdirect-access-external-data.
1665   Opts.DirectAccessExternalData =
1666       Args.hasArg(OPT_fdirect_access_external_data) ||
1667       (!Args.hasArg(OPT_fno_direct_access_external_data) &&
1668        LangOpts->PICLevel == 0);
1669 
1670   if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
1671     unsigned Val =
1672         llvm::StringSwitch<unsigned>(A->getValue())
1673             .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly)
1674             .Case("line-directives-only",
1675                   llvm::codegenoptions::DebugDirectivesOnly)
1676             .Case("constructor", llvm::codegenoptions::DebugInfoConstructor)
1677             .Case("limited", llvm::codegenoptions::LimitedDebugInfo)
1678             .Case("standalone", llvm::codegenoptions::FullDebugInfo)
1679             .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo)
1680             .Default(~0U);
1681     if (Val == ~0U)
1682       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1683                                                 << A->getValue();
1684     else
1685       Opts.setDebugInfo(static_cast<llvm::codegenoptions::DebugInfoKind>(Val));
1686   }
1687 
1688   // If -fuse-ctor-homing is set and limited debug info is already on, then use
1689   // constructor homing, and vice versa for -fno-use-ctor-homing.
1690   if (const Arg *A =
1691           Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
1692     if (A->getOption().matches(OPT_fuse_ctor_homing) &&
1693         Opts.getDebugInfo() == llvm::codegenoptions::LimitedDebugInfo)
1694       Opts.setDebugInfo(llvm::codegenoptions::DebugInfoConstructor);
1695     if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
1696         Opts.getDebugInfo() == llvm::codegenoptions::DebugInfoConstructor)
1697       Opts.setDebugInfo(llvm::codegenoptions::LimitedDebugInfo);
1698   }
1699 
1700   for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
1701     auto Split = StringRef(Arg).split('=');
1702     Opts.DebugPrefixMap.emplace_back(Split.first, Split.second);
1703   }
1704 
1705   for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
1706     auto Split = StringRef(Arg).split('=');
1707     Opts.CoveragePrefixMap.emplace_back(Split.first, Split.second);
1708   }
1709 
1710   const llvm::Triple::ArchType DebugEntryValueArchs[] = {
1711       llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
1712       llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
1713       llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
1714 
1715   if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
1716       llvm::is_contained(DebugEntryValueArchs, T.getArch()))
1717     Opts.EmitCallSiteInfo = true;
1718 
1719   if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
1720     Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
1721         << Opts.DIBugsReportFilePath;
1722     Opts.DIBugsReportFilePath = "";
1723   }
1724 
1725   Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
1726                            Args.hasArg(OPT_new_struct_path_tbaa);
1727   Opts.OptimizeSize = getOptimizationLevelSize(Args);
1728   Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
1729   if (Opts.SimplifyLibCalls)
1730     Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
1731   Opts.UnrollLoops =
1732       Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
1733                    (Opts.OptimizationLevel > 1));
1734   Opts.BinutilsVersion =
1735       std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
1736 
1737   Opts.DebugNameTable = static_cast<unsigned>(
1738       Args.hasArg(OPT_ggnu_pubnames)
1739           ? llvm::DICompileUnit::DebugNameTableKind::GNU
1740           : Args.hasArg(OPT_gpubnames)
1741                 ? llvm::DICompileUnit::DebugNameTableKind::Default
1742                 : llvm::DICompileUnit::DebugNameTableKind::None);
1743   if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
1744     StringRef Value = A->getValue();
1745     if (Value != "simple" && Value != "mangled")
1746       Diags.Report(diag::err_drv_unsupported_option_argument)
1747           << A->getSpelling() << A->getValue();
1748     Opts.setDebugSimpleTemplateNames(
1749         StringRef(A->getValue()) == "simple"
1750             ? llvm::codegenoptions::DebugTemplateNamesKind::Simple
1751             : llvm::codegenoptions::DebugTemplateNamesKind::Mangled);
1752   }
1753 
1754   if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
1755     Opts.TimePasses = true;
1756 
1757     // -ftime-report= is only for new pass manager.
1758     if (A->getOption().getID() == OPT_ftime_report_EQ) {
1759       StringRef Val = A->getValue();
1760       if (Val == "per-pass")
1761         Opts.TimePassesPerRun = false;
1762       else if (Val == "per-pass-run")
1763         Opts.TimePassesPerRun = true;
1764       else
1765         Diags.Report(diag::err_drv_invalid_value)
1766             << A->getAsString(Args) << A->getValue();
1767     }
1768   }
1769 
1770   Opts.PrepareForLTO = false;
1771   Opts.PrepareForThinLTO = false;
1772   if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
1773     Opts.PrepareForLTO = true;
1774     StringRef S = A->getValue();
1775     if (S == "thin")
1776       Opts.PrepareForThinLTO = true;
1777     else if (S != "full")
1778       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
1779   }
1780   if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
1781     if (IK.getLanguage() != Language::LLVM_IR)
1782       Diags.Report(diag::err_drv_argument_only_allowed_with)
1783           << A->getAsString(Args) << "-x ir";
1784     Opts.ThinLTOIndexFile =
1785         std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
1786   }
1787   if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
1788     Opts.SaveTempsFilePrefix =
1789         llvm::StringSwitch<std::string>(A->getValue())
1790             .Case("obj", OutputFile)
1791             .Default(llvm::sys::path::filename(OutputFile).str());
1792 
1793   // The memory profile runtime appends the pid to make this name more unique.
1794   const char *MemProfileBasename = "memprof.profraw";
1795   if (Args.hasArg(OPT_fmemory_profile_EQ)) {
1796     SmallString<128> Path(
1797         std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
1798     llvm::sys::path::append(Path, MemProfileBasename);
1799     Opts.MemoryProfileOutput = std::string(Path);
1800   } else if (Args.hasArg(OPT_fmemory_profile))
1801     Opts.MemoryProfileOutput = MemProfileBasename;
1802 
1803   memcpy(Opts.CoverageVersion, "408*", 4);
1804   if (Opts.CoverageNotesFile.size() || Opts.CoverageDataFile.size()) {
1805     if (Args.hasArg(OPT_coverage_version_EQ)) {
1806       StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
1807       if (CoverageVersion.size() != 4) {
1808         Diags.Report(diag::err_drv_invalid_value)
1809             << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
1810             << CoverageVersion;
1811       } else {
1812         memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
1813       }
1814     }
1815   }
1816   // FIXME: For backend options that are not yet recorded as function
1817   // attributes in the IR, keep track of them so we can embed them in a
1818   // separate data section and use them when building the bitcode.
1819   for (const auto &A : Args) {
1820     // Do not encode output and input.
1821     if (A->getOption().getID() == options::OPT_o ||
1822         A->getOption().getID() == options::OPT_INPUT ||
1823         A->getOption().getID() == options::OPT_x ||
1824         A->getOption().getID() == options::OPT_fembed_bitcode ||
1825         A->getOption().matches(options::OPT_W_Group))
1826       continue;
1827     ArgStringList ASL;
1828     A->render(Args, ASL);
1829     for (const auto &arg : ASL) {
1830       StringRef ArgStr(arg);
1831       Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1832       // using \00 to separate each commandline options.
1833       Opts.CmdArgs.push_back('\0');
1834     }
1835   }
1836 
1837   auto XRayInstrBundles =
1838       Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1839   if (XRayInstrBundles.empty())
1840     Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
1841   else
1842     for (const auto &A : XRayInstrBundles)
1843       parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1844                                      Diags, Opts.XRayInstrumentationBundle);
1845 
1846   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1847     StringRef Name = A->getValue();
1848     if (Name == "full") {
1849       Opts.CFProtectionReturn = 1;
1850       Opts.CFProtectionBranch = 1;
1851     } else if (Name == "return")
1852       Opts.CFProtectionReturn = 1;
1853     else if (Name == "branch")
1854       Opts.CFProtectionBranch = 1;
1855     else if (Name != "none")
1856       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1857   }
1858 
1859   if (const Arg *A = Args.getLastArg(OPT_mfunction_return_EQ)) {
1860     auto Val = llvm::StringSwitch<llvm::FunctionReturnThunksKind>(A->getValue())
1861                    .Case("keep", llvm::FunctionReturnThunksKind::Keep)
1862                    .Case("thunk-extern", llvm::FunctionReturnThunksKind::Extern)
1863                    .Default(llvm::FunctionReturnThunksKind::Invalid);
1864     // SystemZ might want to add support for "expolines."
1865     if (!T.isX86())
1866       Diags.Report(diag::err_drv_argument_not_allowed_with)
1867           << A->getSpelling() << T.getTriple();
1868     else if (Val == llvm::FunctionReturnThunksKind::Invalid)
1869       Diags.Report(diag::err_drv_invalid_value)
1870           << A->getAsString(Args) << A->getValue();
1871     else if (Val == llvm::FunctionReturnThunksKind::Extern &&
1872              Args.getLastArgValue(OPT_mcmodel_EQ).equals("large"))
1873       Diags.Report(diag::err_drv_argument_not_allowed_with)
1874           << A->getAsString(Args)
1875           << Args.getLastArg(OPT_mcmodel_EQ)->getAsString(Args);
1876     else
1877       Opts.FunctionReturnThunks = static_cast<unsigned>(Val);
1878   }
1879 
1880   for (auto *A :
1881        Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1882     CodeGenOptions::BitcodeFileToLink F;
1883     F.Filename = A->getValue();
1884     if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1885       F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
1886       // When linking CUDA bitcode, propagate function attributes so that
1887       // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1888       F.PropagateAttrs = true;
1889       F.Internalize = true;
1890     }
1891     Opts.LinkBitcodeFiles.push_back(F);
1892   }
1893 
1894   if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
1895     if (T.isOSAIX()) {
1896       StringRef Name = A->getValue();
1897       if (Name != "global-dynamic")
1898         Diags.Report(diag::err_aix_unsupported_tls_model) << Name;
1899     }
1900   }
1901 
1902   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1903     StringRef Val = A->getValue();
1904     Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
1905     Opts.FP32DenormalMode = Opts.FPDenormalMode;
1906     if (!Opts.FPDenormalMode.isValid())
1907       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1908   }
1909 
1910   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
1911     StringRef Val = A->getValue();
1912     Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
1913     if (!Opts.FP32DenormalMode.isValid())
1914       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1915   }
1916 
1917   // X86_32 has -fppc-struct-return and -freg-struct-return.
1918   // PPC32 has -maix-struct-return and -msvr4-struct-return.
1919   if (Arg *A =
1920           Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
1921                           OPT_maix_struct_return, OPT_msvr4_struct_return)) {
1922     // TODO: We might want to consider enabling these options on AIX in the
1923     // future.
1924     if (T.isOSAIX())
1925       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1926           << A->getSpelling() << T.str();
1927 
1928     const Option &O = A->getOption();
1929     if (O.matches(OPT_fpcc_struct_return) ||
1930         O.matches(OPT_maix_struct_return)) {
1931       Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1932     } else {
1933       assert(O.matches(OPT_freg_struct_return) ||
1934              O.matches(OPT_msvr4_struct_return));
1935       Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1936     }
1937   }
1938 
1939   if (Arg *A = Args.getLastArg(OPT_mxcoff_roptr)) {
1940     if (!T.isOSAIX())
1941       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1942           << A->getSpelling() << T.str();
1943 
1944     // Since the storage mapping class is specified per csect,
1945     // without using data sections, it is less effective to use read-only
1946     // pointers. Using read-only pointers may cause other RO variables in the
1947     // same csect to become RW when the linker acts upon `-bforceimprw`;
1948     // therefore, we require that separate data sections
1949     // are used when `-mxcoff-roptr` is in effect. We respect the setting of
1950     // data-sections since we have not found reasons to do otherwise that
1951     // overcome the user surprise of not respecting the setting.
1952     if (!Args.hasFlag(OPT_fdata_sections, OPT_fno_data_sections, false))
1953       Diags.Report(diag::err_roptr_requires_data_sections);
1954 
1955     Opts.XCOFFReadOnlyPointers = true;
1956   }
1957 
1958   if (Arg *A = Args.getLastArg(OPT_mabi_EQ_quadword_atomics)) {
1959     if (!T.isOSAIX() || T.isPPC32())
1960       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1961         << A->getSpelling() << T.str();
1962   }
1963 
1964   bool NeedLocTracking = false;
1965 
1966   if (!Opts.OptRecordFile.empty())
1967     NeedLocTracking = true;
1968 
1969   if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
1970     Opts.OptRecordPasses = A->getValue();
1971     NeedLocTracking = true;
1972   }
1973 
1974   if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
1975     Opts.OptRecordFormat = A->getValue();
1976     NeedLocTracking = true;
1977   }
1978 
1979   Opts.OptimizationRemark =
1980       ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
1981 
1982   Opts.OptimizationRemarkMissed =
1983       ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed");
1984 
1985   Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark(
1986       Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
1987 
1988   NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
1989                      Opts.OptimizationRemarkMissed.hasValidPattern() ||
1990                      Opts.OptimizationRemarkAnalysis.hasValidPattern();
1991 
1992   bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
1993   bool UsingProfile =
1994       UsingSampleProfile || !Opts.ProfileInstrumentUsePath.empty();
1995 
1996   if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1997       // An IR file will contain PGO as metadata
1998       IK.getLanguage() != Language::LLVM_IR)
1999     Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
2000         << "-fdiagnostics-show-hotness";
2001 
2002   // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
2003   if (auto *arg =
2004           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2005     auto ResultOrErr =
2006         llvm::remarks::parseHotnessThresholdOption(arg->getValue());
2007 
2008     if (!ResultOrErr) {
2009       Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
2010           << "-fdiagnostics-hotness-threshold=";
2011     } else {
2012       Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
2013       if ((!Opts.DiagnosticsHotnessThreshold ||
2014            *Opts.DiagnosticsHotnessThreshold > 0) &&
2015           !UsingProfile)
2016         Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
2017             << "-fdiagnostics-hotness-threshold=";
2018     }
2019   }
2020 
2021   if (auto *arg =
2022           Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
2023     auto ResultOrErr = parseToleranceOption(arg->getValue());
2024 
2025     if (!ResultOrErr) {
2026       Diags.Report(diag::err_drv_invalid_diagnotics_misexpect_tolerance)
2027           << "-fdiagnostics-misexpect-tolerance=";
2028     } else {
2029       Opts.DiagnosticsMisExpectTolerance = *ResultOrErr;
2030       if ((!Opts.DiagnosticsMisExpectTolerance ||
2031            *Opts.DiagnosticsMisExpectTolerance > 0) &&
2032           !UsingProfile)
2033         Diags.Report(diag::warn_drv_diagnostics_misexpect_requires_pgo)
2034             << "-fdiagnostics-misexpect-tolerance=";
2035     }
2036   }
2037 
2038   // If the user requested to use a sample profile for PGO, then the
2039   // backend will need to track source location information so the profile
2040   // can be incorporated into the IR.
2041   if (UsingSampleProfile)
2042     NeedLocTracking = true;
2043 
2044   if (!Opts.StackUsageOutput.empty())
2045     NeedLocTracking = true;
2046 
2047   // If the user requested a flag that requires source locations available in
2048   // the backend, make sure that the backend tracks source location information.
2049   if (NeedLocTracking &&
2050       Opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo)
2051     Opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly);
2052 
2053   // Parse -fsanitize-recover= arguments.
2054   // FIXME: Report unrecoverable sanitizers incorrectly specified here.
2055   parseSanitizerKinds("-fsanitize-recover=",
2056                       Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
2057                       Opts.SanitizeRecover);
2058   parseSanitizerKinds("-fsanitize-trap=",
2059                       Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
2060                       Opts.SanitizeTrap);
2061 
2062   Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
2063 
2064   if (Args.hasArg(options::OPT_ffinite_loops))
2065     Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
2066   else if (Args.hasArg(options::OPT_fno_finite_loops))
2067     Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
2068 
2069   Opts.EmitIEEENaNCompliantInsts = Args.hasFlag(
2070       options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee, true);
2071   if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
2072     Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
2073 
2074   return Diags.getNumErrors() == NumErrorsBefore;
2075 }
2076 
2077 static void
2078 GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
2079                              SmallVectorImpl<const char *> &Args,
2080                              CompilerInvocation::StringAllocator SA) {
2081   const DependencyOutputOptions &DependencyOutputOpts = Opts;
2082 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...)                         \
2083   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
2084 #include "clang/Driver/Options.inc"
2085 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2086 
2087   if (Opts.ShowIncludesDest != ShowIncludesDestination::None)
2088     GenerateArg(Args, OPT_show_includes, SA);
2089 
2090   for (const auto &Dep : Opts.ExtraDeps) {
2091     switch (Dep.second) {
2092     case EDK_SanitizeIgnorelist:
2093       // Sanitizer ignorelist arguments are generated from LanguageOptions.
2094       continue;
2095     case EDK_ModuleFile:
2096       // Module file arguments are generated from FrontendOptions and
2097       // HeaderSearchOptions.
2098       continue;
2099     case EDK_ProfileList:
2100       // Profile list arguments are generated from LanguageOptions via the
2101       // marshalling infrastructure.
2102       continue;
2103     case EDK_DepFileEntry:
2104       GenerateArg(Args, OPT_fdepfile_entry, Dep.first, SA);
2105       break;
2106     }
2107   }
2108 }
2109 
2110 static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
2111                                       ArgList &Args, DiagnosticsEngine &Diags,
2112                                       frontend::ActionKind Action,
2113                                       bool ShowLineMarkers) {
2114   unsigned NumErrorsBefore = Diags.getNumErrors();
2115 
2116   DependencyOutputOptions &DependencyOutputOpts = Opts;
2117 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...)                         \
2118   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2119 #include "clang/Driver/Options.inc"
2120 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2121 
2122   if (Args.hasArg(OPT_show_includes)) {
2123     // Writing both /showIncludes and preprocessor output to stdout
2124     // would produce interleaved output, so use stderr for /showIncludes.
2125     // This behaves the same as cl.exe, when /E, /EP or /P are passed.
2126     if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
2127       Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
2128     else
2129       Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
2130   } else {
2131     Opts.ShowIncludesDest = ShowIncludesDestination::None;
2132   }
2133 
2134   // Add sanitizer ignorelists as extra dependencies.
2135   // They won't be discovered by the regular preprocessor, so
2136   // we let make / ninja to know about this implicit dependency.
2137   if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) {
2138     for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) {
2139       StringRef Val = A->getValue();
2140       if (!Val.contains('='))
2141         Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2142     }
2143     if (Opts.IncludeSystemHeaders) {
2144       for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) {
2145         StringRef Val = A->getValue();
2146         if (!Val.contains('='))
2147           Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2148       }
2149     }
2150   }
2151 
2152   // -fprofile-list= dependencies.
2153   for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
2154     Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList);
2155 
2156   // Propagate the extra dependencies.
2157   for (const auto *A : Args.filtered(OPT_fdepfile_entry))
2158     Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry);
2159 
2160   // Only the -fmodule-file=<file> form.
2161   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2162     StringRef Val = A->getValue();
2163     if (!Val.contains('='))
2164       Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile);
2165   }
2166 
2167   // Check for invalid combinations of header-include-format
2168   // and header-include-filtering.
2169   if ((Opts.HeaderIncludeFormat == HIFMT_Textual &&
2170        Opts.HeaderIncludeFiltering != HIFIL_None) ||
2171       (Opts.HeaderIncludeFormat == HIFMT_JSON &&
2172        Opts.HeaderIncludeFiltering != HIFIL_Only_Direct_System))
2173     Diags.Report(diag::err_drv_print_header_env_var_combination_cc1)
2174         << Args.getLastArg(OPT_header_include_format_EQ)->getValue()
2175         << Args.getLastArg(OPT_header_include_filtering_EQ)->getValue();
2176 
2177   return Diags.getNumErrors() == NumErrorsBefore;
2178 }
2179 
2180 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
2181   // Color diagnostics default to auto ("on" if terminal supports) in the driver
2182   // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
2183   // Support both clang's -f[no-]color-diagnostics and gcc's
2184   // -f[no-]diagnostics-colors[=never|always|auto].
2185   enum {
2186     Colors_On,
2187     Colors_Off,
2188     Colors_Auto
2189   } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
2190   for (auto *A : Args) {
2191     const Option &O = A->getOption();
2192     if (O.matches(options::OPT_fcolor_diagnostics)) {
2193       ShowColors = Colors_On;
2194     } else if (O.matches(options::OPT_fno_color_diagnostics)) {
2195       ShowColors = Colors_Off;
2196     } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2197       StringRef Value(A->getValue());
2198       if (Value == "always")
2199         ShowColors = Colors_On;
2200       else if (Value == "never")
2201         ShowColors = Colors_Off;
2202       else if (Value == "auto")
2203         ShowColors = Colors_Auto;
2204     }
2205   }
2206   return ShowColors == Colors_On ||
2207          (ShowColors == Colors_Auto &&
2208           llvm::sys::Process::StandardErrHasColors());
2209 }
2210 
2211 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
2212                                 DiagnosticsEngine &Diags) {
2213   bool Success = true;
2214   for (const auto &Prefix : VerifyPrefixes) {
2215     // Every prefix must start with a letter and contain only alphanumeric
2216     // characters, hyphens, and underscores.
2217     auto BadChar = llvm::find_if(Prefix, [](char C) {
2218       return !isAlphanumeric(C) && C != '-' && C != '_';
2219     });
2220     if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
2221       Success = false;
2222       Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
2223       Diags.Report(diag::note_drv_verify_prefix_spelling);
2224     }
2225   }
2226   return Success;
2227 }
2228 
2229 static void GenerateFileSystemArgs(const FileSystemOptions &Opts,
2230                                    SmallVectorImpl<const char *> &Args,
2231                                    CompilerInvocation::StringAllocator SA) {
2232   const FileSystemOptions &FileSystemOpts = Opts;
2233 
2234 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...)                               \
2235   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
2236 #include "clang/Driver/Options.inc"
2237 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2238 }
2239 
2240 static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
2241                                 DiagnosticsEngine &Diags) {
2242   unsigned NumErrorsBefore = Diags.getNumErrors();
2243 
2244   FileSystemOptions &FileSystemOpts = Opts;
2245 
2246 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...)                               \
2247   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2248 #include "clang/Driver/Options.inc"
2249 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2250 
2251   return Diags.getNumErrors() == NumErrorsBefore;
2252 }
2253 
2254 static void GenerateMigratorArgs(const MigratorOptions &Opts,
2255                                  SmallVectorImpl<const char *> &Args,
2256                                  CompilerInvocation::StringAllocator SA) {
2257   const MigratorOptions &MigratorOpts = Opts;
2258 #define MIGRATOR_OPTION_WITH_MARSHALLING(...)                                  \
2259   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
2260 #include "clang/Driver/Options.inc"
2261 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2262 }
2263 
2264 static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
2265                               DiagnosticsEngine &Diags) {
2266   unsigned NumErrorsBefore = Diags.getNumErrors();
2267 
2268   MigratorOptions &MigratorOpts = Opts;
2269 
2270 #define MIGRATOR_OPTION_WITH_MARSHALLING(...)                                  \
2271   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2272 #include "clang/Driver/Options.inc"
2273 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2274 
2275   return Diags.getNumErrors() == NumErrorsBefore;
2276 }
2277 
2278 void CompilerInvocation::GenerateDiagnosticArgs(
2279     const DiagnosticOptions &Opts, SmallVectorImpl<const char *> &Args,
2280     StringAllocator SA, bool DefaultDiagColor) {
2281   const DiagnosticOptions *DiagnosticOpts = &Opts;
2282 #define DIAG_OPTION_WITH_MARSHALLING(...)                                      \
2283   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
2284 #include "clang/Driver/Options.inc"
2285 #undef DIAG_OPTION_WITH_MARSHALLING
2286 
2287   if (!Opts.DiagnosticSerializationFile.empty())
2288     GenerateArg(Args, OPT_diagnostic_serialized_file,
2289                 Opts.DiagnosticSerializationFile, SA);
2290 
2291   if (Opts.ShowColors)
2292     GenerateArg(Args, OPT_fcolor_diagnostics, SA);
2293 
2294   if (Opts.VerifyDiagnostics &&
2295       llvm::is_contained(Opts.VerifyPrefixes, "expected"))
2296     GenerateArg(Args, OPT_verify, SA);
2297 
2298   for (const auto &Prefix : Opts.VerifyPrefixes)
2299     if (Prefix != "expected")
2300       GenerateArg(Args, OPT_verify_EQ, Prefix, SA);
2301 
2302   DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
2303   if (VIU == DiagnosticLevelMask::None) {
2304     // This is the default, don't generate anything.
2305   } else if (VIU == DiagnosticLevelMask::All) {
2306     GenerateArg(Args, OPT_verify_ignore_unexpected, SA);
2307   } else {
2308     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
2309       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "note", SA);
2310     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
2311       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "remark", SA);
2312     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
2313       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "warning", SA);
2314     if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
2315       GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "error", SA);
2316   }
2317 
2318   for (const auto &Warning : Opts.Warnings) {
2319     // This option is automatically generated from UndefPrefixes.
2320     if (Warning == "undef-prefix")
2321       continue;
2322     Args.push_back(SA(StringRef("-W") + Warning));
2323   }
2324 
2325   for (const auto &Remark : Opts.Remarks) {
2326     // These arguments are generated from OptimizationRemark fields of
2327     // CodeGenOptions.
2328     StringRef IgnoredRemarks[] = {"pass",          "no-pass",
2329                                   "pass-analysis", "no-pass-analysis",
2330                                   "pass-missed",   "no-pass-missed"};
2331     if (llvm::is_contained(IgnoredRemarks, Remark))
2332       continue;
2333 
2334     Args.push_back(SA(StringRef("-R") + Remark));
2335   }
2336 }
2337 
2338 std::unique_ptr<DiagnosticOptions>
2339 clang::CreateAndPopulateDiagOpts(ArrayRef<const char *> Argv) {
2340   auto DiagOpts = std::make_unique<DiagnosticOptions>();
2341   unsigned MissingArgIndex, MissingArgCount;
2342   InputArgList Args = getDriverOptTable().ParseArgs(
2343       Argv.slice(1), MissingArgIndex, MissingArgCount);
2344   // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
2345   // Any errors that would be diagnosed here will also be diagnosed later,
2346   // when the DiagnosticsEngine actually exists.
2347   (void)ParseDiagnosticArgs(*DiagOpts, Args);
2348   return DiagOpts;
2349 }
2350 
2351 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
2352                                 DiagnosticsEngine *Diags,
2353                                 bool DefaultDiagColor) {
2354   std::optional<DiagnosticsEngine> IgnoringDiags;
2355   if (!Diags) {
2356     IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(),
2357                           new IgnoringDiagConsumer());
2358     Diags = &*IgnoringDiags;
2359   }
2360 
2361   unsigned NumErrorsBefore = Diags->getNumErrors();
2362 
2363   // The key paths of diagnostic options defined in Options.td start with
2364   // "DiagnosticOpts->". Let's provide the expected variable name and type.
2365   DiagnosticOptions *DiagnosticOpts = &Opts;
2366 
2367 #define DIAG_OPTION_WITH_MARSHALLING(...)                                      \
2368   PARSE_OPTION_WITH_MARSHALLING(Args, *Diags, __VA_ARGS__)
2369 #include "clang/Driver/Options.inc"
2370 #undef DIAG_OPTION_WITH_MARSHALLING
2371 
2372   llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
2373 
2374   if (Arg *A =
2375           Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
2376     Opts.DiagnosticSerializationFile = A->getValue();
2377   Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
2378 
2379   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
2380   Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
2381   if (Args.hasArg(OPT_verify))
2382     Opts.VerifyPrefixes.push_back("expected");
2383   // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
2384   // then sort it to prepare for fast lookup using std::binary_search.
2385   if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags))
2386     Opts.VerifyDiagnostics = false;
2387   else
2388     llvm::sort(Opts.VerifyPrefixes);
2389   DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
2390   parseDiagnosticLevelMask(
2391       "-verify-ignore-unexpected=",
2392       Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask);
2393   if (Args.hasArg(OPT_verify_ignore_unexpected))
2394     DiagMask = DiagnosticLevelMask::All;
2395   Opts.setVerifyIgnoreUnexpected(DiagMask);
2396   if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
2397     Diags->Report(diag::warn_ignoring_ftabstop_value)
2398         << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
2399     Opts.TabStop = DiagnosticOptions::DefaultTabStop;
2400   }
2401 
2402   addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
2403   addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
2404 
2405   return Diags->getNumErrors() == NumErrorsBefore;
2406 }
2407 
2408 /// Parse the argument to the -ftest-module-file-extension
2409 /// command-line argument.
2410 ///
2411 /// \returns true on error, false on success.
2412 static bool parseTestModuleFileExtensionArg(StringRef Arg,
2413                                             std::string &BlockName,
2414                                             unsigned &MajorVersion,
2415                                             unsigned &MinorVersion,
2416                                             bool &Hashed,
2417                                             std::string &UserInfo) {
2418   SmallVector<StringRef, 5> Args;
2419   Arg.split(Args, ':', 5);
2420   if (Args.size() < 5)
2421     return true;
2422 
2423   BlockName = std::string(Args[0]);
2424   if (Args[1].getAsInteger(10, MajorVersion)) return true;
2425   if (Args[2].getAsInteger(10, MinorVersion)) return true;
2426   if (Args[3].getAsInteger(2, Hashed)) return true;
2427   if (Args.size() > 4)
2428     UserInfo = std::string(Args[4]);
2429   return false;
2430 }
2431 
2432 /// Return a table that associates command line option specifiers with the
2433 /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
2434 /// intentionally missing, as this case is handled separately from other
2435 /// frontend options.
2436 static const auto &getFrontendActionTable() {
2437   static const std::pair<frontend::ActionKind, unsigned> Table[] = {
2438       {frontend::ASTDeclList, OPT_ast_list},
2439 
2440       {frontend::ASTDump, OPT_ast_dump_all_EQ},
2441       {frontend::ASTDump, OPT_ast_dump_all},
2442       {frontend::ASTDump, OPT_ast_dump_EQ},
2443       {frontend::ASTDump, OPT_ast_dump},
2444       {frontend::ASTDump, OPT_ast_dump_lookups},
2445       {frontend::ASTDump, OPT_ast_dump_decl_types},
2446 
2447       {frontend::ASTPrint, OPT_ast_print},
2448       {frontend::ASTView, OPT_ast_view},
2449       {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
2450       {frontend::DumpRawTokens, OPT_dump_raw_tokens},
2451       {frontend::DumpTokens, OPT_dump_tokens},
2452       {frontend::EmitAssembly, OPT_S},
2453       {frontend::EmitBC, OPT_emit_llvm_bc},
2454       {frontend::EmitHTML, OPT_emit_html},
2455       {frontend::EmitLLVM, OPT_emit_llvm},
2456       {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
2457       {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
2458       {frontend::EmitObj, OPT_emit_obj},
2459       {frontend::ExtractAPI, OPT_extract_api},
2460 
2461       {frontend::FixIt, OPT_fixit_EQ},
2462       {frontend::FixIt, OPT_fixit},
2463 
2464       {frontend::GenerateModule, OPT_emit_module},
2465       {frontend::GenerateModuleInterface, OPT_emit_module_interface},
2466       {frontend::GenerateHeaderUnit, OPT_emit_header_unit},
2467       {frontend::GeneratePCH, OPT_emit_pch},
2468       {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
2469       {frontend::InitOnly, OPT_init_only},
2470       {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
2471       {frontend::ModuleFileInfo, OPT_module_file_info},
2472       {frontend::VerifyPCH, OPT_verify_pch},
2473       {frontend::PrintPreamble, OPT_print_preamble},
2474       {frontend::PrintPreprocessedInput, OPT_E},
2475       {frontend::TemplightDump, OPT_templight_dump},
2476       {frontend::RewriteMacros, OPT_rewrite_macros},
2477       {frontend::RewriteObjC, OPT_rewrite_objc},
2478       {frontend::RewriteTest, OPT_rewrite_test},
2479       {frontend::RunAnalysis, OPT_analyze},
2480       {frontend::MigrateSource, OPT_migrate},
2481       {frontend::RunPreprocessorOnly, OPT_Eonly},
2482       {frontend::PrintDependencyDirectivesSourceMinimizerOutput,
2483        OPT_print_dependency_directives_minimized_source},
2484   };
2485 
2486   return Table;
2487 }
2488 
2489 /// Maps command line option to frontend action.
2490 static std::optional<frontend::ActionKind>
2491 getFrontendAction(OptSpecifier &Opt) {
2492   for (const auto &ActionOpt : getFrontendActionTable())
2493     if (ActionOpt.second == Opt.getID())
2494       return ActionOpt.first;
2495 
2496   return std::nullopt;
2497 }
2498 
2499 /// Maps frontend action to command line option.
2500 static std::optional<OptSpecifier>
2501 getProgramActionOpt(frontend::ActionKind ProgramAction) {
2502   for (const auto &ActionOpt : getFrontendActionTable())
2503     if (ActionOpt.first == ProgramAction)
2504       return OptSpecifier(ActionOpt.second);
2505 
2506   return std::nullopt;
2507 }
2508 
2509 static void GenerateFrontendArgs(const FrontendOptions &Opts,
2510                                  SmallVectorImpl<const char *> &Args,
2511                                  CompilerInvocation::StringAllocator SA,
2512                                  bool IsHeader) {
2513   const FrontendOptions &FrontendOpts = Opts;
2514 #define FRONTEND_OPTION_WITH_MARSHALLING(...)                                  \
2515   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
2516 #include "clang/Driver/Options.inc"
2517 #undef FRONTEND_OPTION_WITH_MARSHALLING
2518 
2519   std::optional<OptSpecifier> ProgramActionOpt =
2520       getProgramActionOpt(Opts.ProgramAction);
2521 
2522   // Generating a simple flag covers most frontend actions.
2523   std::function<void()> GenerateProgramAction = [&]() {
2524     GenerateArg(Args, *ProgramActionOpt, SA);
2525   };
2526 
2527   if (!ProgramActionOpt) {
2528     // PluginAction is the only program action handled separately.
2529     assert(Opts.ProgramAction == frontend::PluginAction &&
2530            "Frontend action without option.");
2531     GenerateProgramAction = [&]() {
2532       GenerateArg(Args, OPT_plugin, Opts.ActionName, SA);
2533     };
2534   }
2535 
2536   // FIXME: Simplify the complex 'AST dump' command line.
2537   if (Opts.ProgramAction == frontend::ASTDump) {
2538     GenerateProgramAction = [&]() {
2539       // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
2540       // marshalling infrastructure.
2541 
2542       if (Opts.ASTDumpFormat != ADOF_Default) {
2543         StringRef Format;
2544         switch (Opts.ASTDumpFormat) {
2545         case ADOF_Default:
2546           llvm_unreachable("Default AST dump format.");
2547         case ADOF_JSON:
2548           Format = "json";
2549           break;
2550         }
2551 
2552         if (Opts.ASTDumpAll)
2553           GenerateArg(Args, OPT_ast_dump_all_EQ, Format, SA);
2554         if (Opts.ASTDumpDecls)
2555           GenerateArg(Args, OPT_ast_dump_EQ, Format, SA);
2556       } else {
2557         if (Opts.ASTDumpAll)
2558           GenerateArg(Args, OPT_ast_dump_all, SA);
2559         if (Opts.ASTDumpDecls)
2560           GenerateArg(Args, OPT_ast_dump, SA);
2561       }
2562     };
2563   }
2564 
2565   if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
2566     GenerateProgramAction = [&]() {
2567       GenerateArg(Args, OPT_fixit_EQ, Opts.FixItSuffix, SA);
2568     };
2569   }
2570 
2571   GenerateProgramAction();
2572 
2573   for (const auto &PluginArgs : Opts.PluginArgs) {
2574     Option Opt = getDriverOptTable().getOption(OPT_plugin_arg);
2575     const char *Spelling =
2576         SA(Opt.getPrefix() + Opt.getName() + PluginArgs.first);
2577     for (const auto &PluginArg : PluginArgs.second)
2578       denormalizeString(Args, Spelling, SA, Opt.getKind(), 0, PluginArg);
2579   }
2580 
2581   for (const auto &Ext : Opts.ModuleFileExtensions)
2582     if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get()))
2583       GenerateArg(Args, OPT_ftest_module_file_extension_EQ, TestExt->str(), SA);
2584 
2585   if (!Opts.CodeCompletionAt.FileName.empty())
2586     GenerateArg(Args, OPT_code_completion_at, Opts.CodeCompletionAt.ToString(),
2587                 SA);
2588 
2589   for (const auto &Plugin : Opts.Plugins)
2590     GenerateArg(Args, OPT_load, Plugin, SA);
2591 
2592   // ASTDumpDecls and ASTDumpAll already handled with ProgramAction.
2593 
2594   for (const auto &ModuleFile : Opts.ModuleFiles)
2595     GenerateArg(Args, OPT_fmodule_file, ModuleFile, SA);
2596 
2597   if (Opts.AuxTargetCPU)
2598     GenerateArg(Args, OPT_aux_target_cpu, *Opts.AuxTargetCPU, SA);
2599 
2600   if (Opts.AuxTargetFeatures)
2601     for (const auto &Feature : *Opts.AuxTargetFeatures)
2602       GenerateArg(Args, OPT_aux_target_feature, Feature, SA);
2603 
2604   {
2605     StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : "";
2606     StringRef ModuleMap =
2607         Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : "";
2608     StringRef HeaderUnit = "";
2609     switch (Opts.DashX.getHeaderUnitKind()) {
2610     case InputKind::HeaderUnit_None:
2611       break;
2612     case InputKind::HeaderUnit_User:
2613       HeaderUnit = "-user";
2614       break;
2615     case InputKind::HeaderUnit_System:
2616       HeaderUnit = "-system";
2617       break;
2618     case InputKind::HeaderUnit_Abs:
2619       HeaderUnit = "-header-unit";
2620       break;
2621     }
2622     StringRef Header = IsHeader ? "-header" : "";
2623 
2624     StringRef Lang;
2625     switch (Opts.DashX.getLanguage()) {
2626     case Language::C:
2627       Lang = "c";
2628       break;
2629     case Language::OpenCL:
2630       Lang = "cl";
2631       break;
2632     case Language::OpenCLCXX:
2633       Lang = "clcpp";
2634       break;
2635     case Language::CUDA:
2636       Lang = "cuda";
2637       break;
2638     case Language::HIP:
2639       Lang = "hip";
2640       break;
2641     case Language::CXX:
2642       Lang = "c++";
2643       break;
2644     case Language::ObjC:
2645       Lang = "objective-c";
2646       break;
2647     case Language::ObjCXX:
2648       Lang = "objective-c++";
2649       break;
2650     case Language::RenderScript:
2651       Lang = "renderscript";
2652       break;
2653     case Language::Asm:
2654       Lang = "assembler-with-cpp";
2655       break;
2656     case Language::Unknown:
2657       assert(Opts.DashX.getFormat() == InputKind::Precompiled &&
2658              "Generating -x argument for unknown language (not precompiled).");
2659       Lang = "ast";
2660       break;
2661     case Language::LLVM_IR:
2662       Lang = "ir";
2663       break;
2664     case Language::HLSL:
2665       Lang = "hlsl";
2666       break;
2667     }
2668 
2669     GenerateArg(Args, OPT_x,
2670                 Lang + HeaderUnit + Header + ModuleMap + Preprocessed, SA);
2671   }
2672 
2673   // OPT_INPUT has a unique class, generate it directly.
2674   for (const auto &Input : Opts.Inputs)
2675     Args.push_back(SA(Input.getFile()));
2676 }
2677 
2678 static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
2679                               DiagnosticsEngine &Diags, bool &IsHeaderFile) {
2680   unsigned NumErrorsBefore = Diags.getNumErrors();
2681 
2682   FrontendOptions &FrontendOpts = Opts;
2683 
2684 #define FRONTEND_OPTION_WITH_MARSHALLING(...)                                  \
2685   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2686 #include "clang/Driver/Options.inc"
2687 #undef FRONTEND_OPTION_WITH_MARSHALLING
2688 
2689   Opts.ProgramAction = frontend::ParseSyntaxOnly;
2690   if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
2691     OptSpecifier Opt = OptSpecifier(A->getOption().getID());
2692     std::optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt);
2693     assert(ProgramAction && "Option specifier not in Action_Group.");
2694 
2695     if (ProgramAction == frontend::ASTDump &&
2696         (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
2697       unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
2698                          .CaseLower("default", ADOF_Default)
2699                          .CaseLower("json", ADOF_JSON)
2700                          .Default(std::numeric_limits<unsigned>::max());
2701 
2702       if (Val != std::numeric_limits<unsigned>::max())
2703         Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
2704       else {
2705         Diags.Report(diag::err_drv_invalid_value)
2706             << A->getAsString(Args) << A->getValue();
2707         Opts.ASTDumpFormat = ADOF_Default;
2708       }
2709     }
2710 
2711     if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ)
2712       Opts.FixItSuffix = A->getValue();
2713 
2714     if (ProgramAction == frontend::GenerateInterfaceStubs) {
2715       StringRef ArgStr =
2716           Args.hasArg(OPT_interface_stub_version_EQ)
2717               ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
2718               : "ifs-v1";
2719       if (ArgStr == "experimental-yaml-elf-v1" ||
2720           ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-ifs-v2" ||
2721           ArgStr == "experimental-tapi-elf-v1") {
2722         std::string ErrorMessage =
2723             "Invalid interface stub format: " + ArgStr.str() +
2724             " is deprecated.";
2725         Diags.Report(diag::err_drv_invalid_value)
2726             << "Must specify a valid interface stub format type, ie: "
2727                "-interface-stub-version=ifs-v1"
2728             << ErrorMessage;
2729         ProgramAction = frontend::ParseSyntaxOnly;
2730       } else if (!ArgStr.startswith("ifs-")) {
2731         std::string ErrorMessage =
2732             "Invalid interface stub format: " + ArgStr.str() + ".";
2733         Diags.Report(diag::err_drv_invalid_value)
2734             << "Must specify a valid interface stub format type, ie: "
2735                "-interface-stub-version=ifs-v1"
2736             << ErrorMessage;
2737         ProgramAction = frontend::ParseSyntaxOnly;
2738       }
2739     }
2740 
2741     Opts.ProgramAction = *ProgramAction;
2742   }
2743 
2744   if (const Arg* A = Args.getLastArg(OPT_plugin)) {
2745     Opts.Plugins.emplace_back(A->getValue(0));
2746     Opts.ProgramAction = frontend::PluginAction;
2747     Opts.ActionName = A->getValue();
2748   }
2749   for (const auto *AA : Args.filtered(OPT_plugin_arg))
2750     Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
2751 
2752   for (const std::string &Arg :
2753          Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
2754     std::string BlockName;
2755     unsigned MajorVersion;
2756     unsigned MinorVersion;
2757     bool Hashed;
2758     std::string UserInfo;
2759     if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
2760                                         MinorVersion, Hashed, UserInfo)) {
2761       Diags.Report(diag::err_test_module_file_extension_format) << Arg;
2762 
2763       continue;
2764     }
2765 
2766     // Add the testing module file extension.
2767     Opts.ModuleFileExtensions.push_back(
2768         std::make_shared<TestModuleFileExtension>(
2769             BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
2770   }
2771 
2772   if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
2773     Opts.CodeCompletionAt =
2774       ParsedSourceLocation::FromString(A->getValue());
2775     if (Opts.CodeCompletionAt.FileName.empty())
2776       Diags.Report(diag::err_drv_invalid_value)
2777         << A->getAsString(Args) << A->getValue();
2778   }
2779 
2780   Opts.Plugins = Args.getAllArgValues(OPT_load);
2781   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
2782   Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
2783   // Only the -fmodule-file=<file> form.
2784   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2785     StringRef Val = A->getValue();
2786     if (!Val.contains('='))
2787       Opts.ModuleFiles.push_back(std::string(Val));
2788   }
2789 
2790   if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
2791     Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
2792                                                            << "-emit-module";
2793 
2794   if (Args.hasArg(OPT_aux_target_cpu))
2795     Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
2796   if (Args.hasArg(OPT_aux_target_feature))
2797     Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
2798 
2799   if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
2800       Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
2801     Diags.Report(diag::err_drv_argument_not_allowed_with)
2802       << "ARC migration" << "ObjC migration";
2803   }
2804 
2805   InputKind DashX(Language::Unknown);
2806   if (const Arg *A = Args.getLastArg(OPT_x)) {
2807     StringRef XValue = A->getValue();
2808 
2809     // Parse suffixes:
2810     // '<lang>(-[{header-unit,user,system}-]header|[-module-map][-cpp-output])'.
2811     // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
2812     bool Preprocessed = XValue.consume_back("-cpp-output");
2813     bool ModuleMap = XValue.consume_back("-module-map");
2814     // Detect and consume the header indicator.
2815     bool IsHeader =
2816         XValue != "precompiled-header" && XValue.consume_back("-header");
2817 
2818     // If we have c++-{user,system}-header, that indicates a header unit input
2819     // likewise, if the user put -fmodule-header together with a header with an
2820     // absolute path (header-unit-header).
2821     InputKind::HeaderUnitKind HUK = InputKind::HeaderUnit_None;
2822     if (IsHeader || Preprocessed) {
2823       if (XValue.consume_back("-header-unit"))
2824         HUK = InputKind::HeaderUnit_Abs;
2825       else if (XValue.consume_back("-system"))
2826         HUK = InputKind::HeaderUnit_System;
2827       else if (XValue.consume_back("-user"))
2828         HUK = InputKind::HeaderUnit_User;
2829     }
2830 
2831     // The value set by this processing is an un-preprocessed source which is
2832     // not intended to be a module map or header unit.
2833     IsHeaderFile = IsHeader && !Preprocessed && !ModuleMap &&
2834                    HUK == InputKind::HeaderUnit_None;
2835 
2836     // Principal languages.
2837     DashX = llvm::StringSwitch<InputKind>(XValue)
2838                 .Case("c", Language::C)
2839                 .Case("cl", Language::OpenCL)
2840                 .Case("clcpp", Language::OpenCLCXX)
2841                 .Case("cuda", Language::CUDA)
2842                 .Case("hip", Language::HIP)
2843                 .Case("c++", Language::CXX)
2844                 .Case("objective-c", Language::ObjC)
2845                 .Case("objective-c++", Language::ObjCXX)
2846                 .Case("renderscript", Language::RenderScript)
2847                 .Case("hlsl", Language::HLSL)
2848                 .Default(Language::Unknown);
2849 
2850     // "objc[++]-cpp-output" is an acceptable synonym for
2851     // "objective-c[++]-cpp-output".
2852     if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap &&
2853         HUK == InputKind::HeaderUnit_None)
2854       DashX = llvm::StringSwitch<InputKind>(XValue)
2855                   .Case("objc", Language::ObjC)
2856                   .Case("objc++", Language::ObjCXX)
2857                   .Default(Language::Unknown);
2858 
2859     // Some special cases cannot be combined with suffixes.
2860     if (DashX.isUnknown() && !Preprocessed && !IsHeaderFile && !ModuleMap &&
2861         HUK == InputKind::HeaderUnit_None)
2862       DashX = llvm::StringSwitch<InputKind>(XValue)
2863                   .Case("cpp-output", InputKind(Language::C).getPreprocessed())
2864                   .Case("assembler-with-cpp", Language::Asm)
2865                   .Cases("ast", "pcm", "precompiled-header",
2866                          InputKind(Language::Unknown, InputKind::Precompiled))
2867                   .Case("ir", Language::LLVM_IR)
2868                   .Default(Language::Unknown);
2869 
2870     if (DashX.isUnknown())
2871       Diags.Report(diag::err_drv_invalid_value)
2872         << A->getAsString(Args) << A->getValue();
2873 
2874     if (Preprocessed)
2875       DashX = DashX.getPreprocessed();
2876     // A regular header is considered mutually exclusive with a header unit.
2877     if (HUK != InputKind::HeaderUnit_None) {
2878       DashX = DashX.withHeaderUnit(HUK);
2879       IsHeaderFile = true;
2880     } else if (IsHeaderFile)
2881       DashX = DashX.getHeader();
2882     if (ModuleMap)
2883       DashX = DashX.withFormat(InputKind::ModuleMap);
2884   }
2885 
2886   // '-' is the default input if none is given.
2887   std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
2888   Opts.Inputs.clear();
2889   if (Inputs.empty())
2890     Inputs.push_back("-");
2891 
2892   if (DashX.getHeaderUnitKind() != InputKind::HeaderUnit_None &&
2893       Inputs.size() > 1)
2894     Diags.Report(diag::err_drv_header_unit_extra_inputs) << Inputs[1];
2895 
2896   for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
2897     InputKind IK = DashX;
2898     if (IK.isUnknown()) {
2899       IK = FrontendOptions::getInputKindForExtension(
2900         StringRef(Inputs[i]).rsplit('.').second);
2901       // FIXME: Warn on this?
2902       if (IK.isUnknown())
2903         IK = Language::C;
2904       // FIXME: Remove this hack.
2905       if (i == 0)
2906         DashX = IK;
2907     }
2908 
2909     bool IsSystem = false;
2910 
2911     // The -emit-module action implicitly takes a module map.
2912     if (Opts.ProgramAction == frontend::GenerateModule &&
2913         IK.getFormat() == InputKind::Source) {
2914       IK = IK.withFormat(InputKind::ModuleMap);
2915       IsSystem = Opts.IsSystemModule;
2916     }
2917 
2918     Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
2919   }
2920 
2921   Opts.DashX = DashX;
2922 
2923   return Diags.getNumErrors() == NumErrorsBefore;
2924 }
2925 
2926 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
2927                                                  void *MainAddr) {
2928   std::string ClangExecutable =
2929       llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
2930   return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
2931 }
2932 
2933 static void GenerateHeaderSearchArgs(HeaderSearchOptions &Opts,
2934                                      SmallVectorImpl<const char *> &Args,
2935                                      CompilerInvocation::StringAllocator SA) {
2936   const HeaderSearchOptions *HeaderSearchOpts = &Opts;
2937 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...)                             \
2938   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
2939 #include "clang/Driver/Options.inc"
2940 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
2941 
2942   if (Opts.UseLibcxx)
2943     GenerateArg(Args, OPT_stdlib_EQ, "libc++", SA);
2944 
2945   if (!Opts.ModuleCachePath.empty())
2946     GenerateArg(Args, OPT_fmodules_cache_path, Opts.ModuleCachePath, SA);
2947 
2948   for (const auto &File : Opts.PrebuiltModuleFiles)
2949     GenerateArg(Args, OPT_fmodule_file, File.first + "=" + File.second, SA);
2950 
2951   for (const auto &Path : Opts.PrebuiltModulePaths)
2952     GenerateArg(Args, OPT_fprebuilt_module_path, Path, SA);
2953 
2954   for (const auto &Macro : Opts.ModulesIgnoreMacros)
2955     GenerateArg(Args, OPT_fmodules_ignore_macro, Macro.val(), SA);
2956 
2957   auto Matches = [](const HeaderSearchOptions::Entry &Entry,
2958                     llvm::ArrayRef<frontend::IncludeDirGroup> Groups,
2959                     std::optional<bool> IsFramework,
2960                     std::optional<bool> IgnoreSysRoot) {
2961     return llvm::is_contained(Groups, Entry.Group) &&
2962            (!IsFramework || (Entry.IsFramework == *IsFramework)) &&
2963            (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot));
2964   };
2965 
2966   auto It = Opts.UserEntries.begin();
2967   auto End = Opts.UserEntries.end();
2968 
2969   // Add -I..., -F..., and -index-header-map options in order.
2970   for (; It < End && Matches(*It, {frontend::IndexHeaderMap, frontend::Angled},
2971                              std::nullopt, true);
2972        ++It) {
2973     OptSpecifier Opt = [It, Matches]() {
2974       if (Matches(*It, frontend::IndexHeaderMap, true, true))
2975         return OPT_F;
2976       if (Matches(*It, frontend::IndexHeaderMap, false, true))
2977         return OPT_I;
2978       if (Matches(*It, frontend::Angled, true, true))
2979         return OPT_F;
2980       if (Matches(*It, frontend::Angled, false, true))
2981         return OPT_I;
2982       llvm_unreachable("Unexpected HeaderSearchOptions::Entry.");
2983     }();
2984 
2985     if (It->Group == frontend::IndexHeaderMap)
2986       GenerateArg(Args, OPT_index_header_map, SA);
2987     GenerateArg(Args, Opt, It->Path, SA);
2988   };
2989 
2990   // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may
2991   // have already been generated as "-I[xx]yy". If that's the case, their
2992   // position on command line was such that this has no semantic impact on
2993   // include paths.
2994   for (; It < End &&
2995          Matches(*It, {frontend::After, frontend::Angled}, false, true);
2996        ++It) {
2997     OptSpecifier Opt =
2998         It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
2999     GenerateArg(Args, Opt, It->Path, SA);
3000   }
3001 
3002   // Note: Some paths that came from "-idirafter=xxyy" may have already been
3003   // generated as "-iwithprefix=xxyy". If that's the case, their position on
3004   // command line was such that this has no semantic impact on include paths.
3005   for (; It < End && Matches(*It, {frontend::After}, false, true); ++It)
3006     GenerateArg(Args, OPT_idirafter, It->Path, SA);
3007   for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It)
3008     GenerateArg(Args, OPT_iquote, It->Path, SA);
3009   for (; It < End && Matches(*It, {frontend::System}, false, std::nullopt);
3010        ++It)
3011     GenerateArg(Args, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
3012                 It->Path, SA);
3013   for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
3014     GenerateArg(Args, OPT_iframework, It->Path, SA);
3015   for (; It < End && Matches(*It, {frontend::System}, true, false); ++It)
3016     GenerateArg(Args, OPT_iframeworkwithsysroot, It->Path, SA);
3017 
3018   // Add the paths for the various language specific isystem flags.
3019   for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It)
3020     GenerateArg(Args, OPT_c_isystem, It->Path, SA);
3021   for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It)
3022     GenerateArg(Args, OPT_cxx_isystem, It->Path, SA);
3023   for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It)
3024     GenerateArg(Args, OPT_objc_isystem, It->Path, SA);
3025   for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It)
3026     GenerateArg(Args, OPT_objcxx_isystem, It->Path, SA);
3027 
3028   // Add the internal paths from a driver that detects standard include paths.
3029   // Note: Some paths that came from "-internal-isystem" arguments may have
3030   // already been generated as "-isystem". If that's the case, their position on
3031   // command line was such that this has no semantic impact on include paths.
3032   for (; It < End &&
3033          Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true);
3034        ++It) {
3035     OptSpecifier Opt = It->Group == frontend::System
3036                            ? OPT_internal_isystem
3037                            : OPT_internal_externc_isystem;
3038     GenerateArg(Args, Opt, It->Path, SA);
3039   }
3040 
3041   assert(It == End && "Unhandled HeaderSearchOption::Entry.");
3042 
3043   // Add the path prefixes which are implicitly treated as being system headers.
3044   for (const auto &P : Opts.SystemHeaderPrefixes) {
3045     OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix
3046                                         : OPT_no_system_header_prefix;
3047     GenerateArg(Args, Opt, P.Prefix, SA);
3048   }
3049 
3050   for (const std::string &F : Opts.VFSOverlayFiles)
3051     GenerateArg(Args, OPT_ivfsoverlay, F, SA);
3052 }
3053 
3054 static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
3055                                   DiagnosticsEngine &Diags,
3056                                   const std::string &WorkingDir) {
3057   unsigned NumErrorsBefore = Diags.getNumErrors();
3058 
3059   HeaderSearchOptions *HeaderSearchOpts = &Opts;
3060 
3061 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...)                             \
3062   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3063 #include "clang/Driver/Options.inc"
3064 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3065 
3066   if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
3067     Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
3068 
3069   // Canonicalize -fmodules-cache-path before storing it.
3070   SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
3071   if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
3072     if (WorkingDir.empty())
3073       llvm::sys::fs::make_absolute(P);
3074     else
3075       llvm::sys::fs::make_absolute(WorkingDir, P);
3076   }
3077   llvm::sys::path::remove_dots(P);
3078   Opts.ModuleCachePath = std::string(P.str());
3079 
3080   // Only the -fmodule-file=<name>=<file> form.
3081   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
3082     StringRef Val = A->getValue();
3083     if (Val.contains('=')) {
3084       auto Split = Val.split('=');
3085       Opts.PrebuiltModuleFiles.insert(
3086           {std::string(Split.first), std::string(Split.second)});
3087     }
3088   }
3089   for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
3090     Opts.AddPrebuiltModulePath(A->getValue());
3091 
3092   for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
3093     StringRef MacroDef = A->getValue();
3094     Opts.ModulesIgnoreMacros.insert(
3095         llvm::CachedHashString(MacroDef.split('=').first));
3096   }
3097 
3098   // Add -I..., -F..., and -index-header-map options in order.
3099   bool IsIndexHeaderMap = false;
3100   bool IsSysrootSpecified =
3101       Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
3102   for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
3103     if (A->getOption().matches(OPT_index_header_map)) {
3104       // -index-header-map applies to the next -I or -F.
3105       IsIndexHeaderMap = true;
3106       continue;
3107     }
3108 
3109     frontend::IncludeDirGroup Group =
3110         IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
3111 
3112     bool IsFramework = A->getOption().matches(OPT_F);
3113     std::string Path = A->getValue();
3114 
3115     if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
3116       SmallString<32> Buffer;
3117       llvm::sys::path::append(Buffer, Opts.Sysroot,
3118                               llvm::StringRef(A->getValue()).substr(1));
3119       Path = std::string(Buffer.str());
3120     }
3121 
3122     Opts.AddPath(Path, Group, IsFramework,
3123                  /*IgnoreSysroot*/ true);
3124     IsIndexHeaderMap = false;
3125   }
3126 
3127   // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
3128   StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
3129   for (const auto *A :
3130        Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
3131     if (A->getOption().matches(OPT_iprefix))
3132       Prefix = A->getValue();
3133     else if (A->getOption().matches(OPT_iwithprefix))
3134       Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
3135     else
3136       Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
3137   }
3138 
3139   for (const auto *A : Args.filtered(OPT_idirafter))
3140     Opts.AddPath(A->getValue(), frontend::After, false, true);
3141   for (const auto *A : Args.filtered(OPT_iquote))
3142     Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
3143   for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
3144     Opts.AddPath(A->getValue(), frontend::System, false,
3145                  !A->getOption().matches(OPT_iwithsysroot));
3146   for (const auto *A : Args.filtered(OPT_iframework))
3147     Opts.AddPath(A->getValue(), frontend::System, true, true);
3148   for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
3149     Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
3150                  /*IgnoreSysRoot=*/false);
3151 
3152   // Add the paths for the various language specific isystem flags.
3153   for (const auto *A : Args.filtered(OPT_c_isystem))
3154     Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
3155   for (const auto *A : Args.filtered(OPT_cxx_isystem))
3156     Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
3157   for (const auto *A : Args.filtered(OPT_objc_isystem))
3158     Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
3159   for (const auto *A : Args.filtered(OPT_objcxx_isystem))
3160     Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
3161 
3162   // Add the internal paths from a driver that detects standard include paths.
3163   for (const auto *A :
3164        Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
3165     frontend::IncludeDirGroup Group = frontend::System;
3166     if (A->getOption().matches(OPT_internal_externc_isystem))
3167       Group = frontend::ExternCSystem;
3168     Opts.AddPath(A->getValue(), Group, false, true);
3169   }
3170 
3171   // Add the path prefixes which are implicitly treated as being system headers.
3172   for (const auto *A :
3173        Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
3174     Opts.AddSystemHeaderPrefix(
3175         A->getValue(), A->getOption().matches(OPT_system_header_prefix));
3176 
3177   for (const auto *A : Args.filtered(OPT_ivfsoverlay, OPT_vfsoverlay))
3178     Opts.AddVFSOverlayFile(A->getValue());
3179 
3180   return Diags.getNumErrors() == NumErrorsBefore;
3181 }
3182 
3183 /// Check if input file kind and language standard are compatible.
3184 static bool IsInputCompatibleWithStandard(InputKind IK,
3185                                           const LangStandard &S) {
3186   switch (IK.getLanguage()) {
3187   case Language::Unknown:
3188   case Language::LLVM_IR:
3189     llvm_unreachable("should not parse language flags for this input");
3190 
3191   case Language::C:
3192   case Language::ObjC:
3193   case Language::RenderScript:
3194     return S.getLanguage() == Language::C;
3195 
3196   case Language::OpenCL:
3197     return S.getLanguage() == Language::OpenCL ||
3198            S.getLanguage() == Language::OpenCLCXX;
3199 
3200   case Language::OpenCLCXX:
3201     return S.getLanguage() == Language::OpenCLCXX;
3202 
3203   case Language::CXX:
3204   case Language::ObjCXX:
3205     return S.getLanguage() == Language::CXX;
3206 
3207   case Language::CUDA:
3208     // FIXME: What -std= values should be permitted for CUDA compilations?
3209     return S.getLanguage() == Language::CUDA ||
3210            S.getLanguage() == Language::CXX;
3211 
3212   case Language::HIP:
3213     return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
3214 
3215   case Language::Asm:
3216     // Accept (and ignore) all -std= values.
3217     // FIXME: The -std= value is not ignored; it affects the tokenization
3218     // and preprocessing rules if we're preprocessing this asm input.
3219     return true;
3220 
3221   case Language::HLSL:
3222     return S.getLanguage() == Language::HLSL;
3223   }
3224 
3225   llvm_unreachable("unexpected input language");
3226 }
3227 
3228 /// Get language name for given input kind.
3229 static StringRef GetInputKindName(InputKind IK) {
3230   switch (IK.getLanguage()) {
3231   case Language::C:
3232     return "C";
3233   case Language::ObjC:
3234     return "Objective-C";
3235   case Language::CXX:
3236     return "C++";
3237   case Language::ObjCXX:
3238     return "Objective-C++";
3239   case Language::OpenCL:
3240     return "OpenCL";
3241   case Language::OpenCLCXX:
3242     return "C++ for OpenCL";
3243   case Language::CUDA:
3244     return "CUDA";
3245   case Language::RenderScript:
3246     return "RenderScript";
3247   case Language::HIP:
3248     return "HIP";
3249 
3250   case Language::Asm:
3251     return "Asm";
3252   case Language::LLVM_IR:
3253     return "LLVM IR";
3254 
3255   case Language::HLSL:
3256     return "HLSL";
3257 
3258   case Language::Unknown:
3259     break;
3260   }
3261   llvm_unreachable("unknown input language");
3262 }
3263 
3264 void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts,
3265                                           SmallVectorImpl<const char *> &Args,
3266                                           StringAllocator SA,
3267                                           const llvm::Triple &T, InputKind IK) {
3268   if (IK.getFormat() == InputKind::Precompiled ||
3269       IK.getLanguage() == Language::LLVM_IR) {
3270     if (Opts.ObjCAutoRefCount)
3271       GenerateArg(Args, OPT_fobjc_arc, SA);
3272     if (Opts.PICLevel != 0)
3273       GenerateArg(Args, OPT_pic_level, Twine(Opts.PICLevel), SA);
3274     if (Opts.PIE)
3275       GenerateArg(Args, OPT_pic_is_pie, SA);
3276     for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3277       GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
3278 
3279     return;
3280   }
3281 
3282   OptSpecifier StdOpt;
3283   switch (Opts.LangStd) {
3284   case LangStandard::lang_opencl10:
3285   case LangStandard::lang_opencl11:
3286   case LangStandard::lang_opencl12:
3287   case LangStandard::lang_opencl20:
3288   case LangStandard::lang_opencl30:
3289   case LangStandard::lang_openclcpp10:
3290   case LangStandard::lang_openclcpp2021:
3291     StdOpt = OPT_cl_std_EQ;
3292     break;
3293   default:
3294     StdOpt = OPT_std_EQ;
3295     break;
3296   }
3297 
3298   auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd);
3299   GenerateArg(Args, StdOpt, LangStandard.getName(), SA);
3300 
3301   if (Opts.IncludeDefaultHeader)
3302     GenerateArg(Args, OPT_finclude_default_header, SA);
3303   if (Opts.DeclareOpenCLBuiltins)
3304     GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
3305 
3306   const LangOptions *LangOpts = &Opts;
3307 
3308 #define LANG_OPTION_WITH_MARSHALLING(...)                                      \
3309   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
3310 #include "clang/Driver/Options.inc"
3311 #undef LANG_OPTION_WITH_MARSHALLING
3312 
3313   // The '-fcf-protection=' option is generated by CodeGenOpts generator.
3314 
3315   if (Opts.ObjC) {
3316     GenerateArg(Args, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString(), SA);
3317 
3318     if (Opts.GC == LangOptions::GCOnly)
3319       GenerateArg(Args, OPT_fobjc_gc_only, SA);
3320     else if (Opts.GC == LangOptions::HybridGC)
3321       GenerateArg(Args, OPT_fobjc_gc, SA);
3322     else if (Opts.ObjCAutoRefCount == 1)
3323       GenerateArg(Args, OPT_fobjc_arc, SA);
3324 
3325     if (Opts.ObjCWeakRuntime)
3326       GenerateArg(Args, OPT_fobjc_runtime_has_weak, SA);
3327 
3328     if (Opts.ObjCWeak)
3329       GenerateArg(Args, OPT_fobjc_weak, SA);
3330 
3331     if (Opts.ObjCSubscriptingLegacyRuntime)
3332       GenerateArg(Args, OPT_fobjc_subscripting_legacy_runtime, SA);
3333   }
3334 
3335   if (Opts.GNUCVersion != 0) {
3336     unsigned Major = Opts.GNUCVersion / 100 / 100;
3337     unsigned Minor = (Opts.GNUCVersion / 100) % 100;
3338     unsigned Patch = Opts.GNUCVersion % 100;
3339     GenerateArg(Args, OPT_fgnuc_version_EQ,
3340                 Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch), SA);
3341   }
3342 
3343   if (Opts.IgnoreXCOFFVisibility)
3344     GenerateArg(Args, OPT_mignore_xcoff_visibility, SA);
3345 
3346   if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) {
3347     GenerateArg(Args, OPT_ftrapv, SA);
3348     GenerateArg(Args, OPT_ftrapv_handler, Opts.OverflowHandler, SA);
3349   } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) {
3350     GenerateArg(Args, OPT_fwrapv, SA);
3351   }
3352 
3353   if (Opts.MSCompatibilityVersion != 0) {
3354     unsigned Major = Opts.MSCompatibilityVersion / 10000000;
3355     unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
3356     unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
3357     GenerateArg(Args, OPT_fms_compatibility_version,
3358                 Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor), SA);
3359   }
3360 
3361   if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS()) {
3362     if (!Opts.Trigraphs)
3363       GenerateArg(Args, OPT_fno_trigraphs, SA);
3364   } else {
3365     if (Opts.Trigraphs)
3366       GenerateArg(Args, OPT_ftrigraphs, SA);
3367   }
3368 
3369   if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
3370     GenerateArg(Args, OPT_fblocks, SA);
3371 
3372   if (Opts.ConvergentFunctions &&
3373       !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice))
3374     GenerateArg(Args, OPT_fconvergent_functions, SA);
3375 
3376   if (Opts.NoBuiltin && !Opts.Freestanding)
3377     GenerateArg(Args, OPT_fno_builtin, SA);
3378 
3379   if (!Opts.NoBuiltin)
3380     for (const auto &Func : Opts.NoBuiltinFuncs)
3381       GenerateArg(Args, OPT_fno_builtin_, Func, SA);
3382 
3383   if (Opts.LongDoubleSize == 128)
3384     GenerateArg(Args, OPT_mlong_double_128, SA);
3385   else if (Opts.LongDoubleSize == 64)
3386     GenerateArg(Args, OPT_mlong_double_64, SA);
3387   else if (Opts.LongDoubleSize == 80)
3388     GenerateArg(Args, OPT_mlong_double_80, SA);
3389 
3390   // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
3391 
3392   // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or
3393   // '-fopenmp-targets='.
3394   if (Opts.OpenMP && !Opts.OpenMPSimd) {
3395     GenerateArg(Args, OPT_fopenmp, SA);
3396 
3397     if (Opts.OpenMP != 50)
3398       GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
3399 
3400     if (!Opts.OpenMPUseTLS)
3401       GenerateArg(Args, OPT_fnoopenmp_use_tls, SA);
3402 
3403     if (Opts.OpenMPIsDevice)
3404       GenerateArg(Args, OPT_fopenmp_is_device, SA);
3405 
3406     if (Opts.OpenMPIRBuilder)
3407       GenerateArg(Args, OPT_fopenmp_enable_irbuilder, SA);
3408   }
3409 
3410   if (Opts.OpenMPSimd) {
3411     GenerateArg(Args, OPT_fopenmp_simd, SA);
3412 
3413     if (Opts.OpenMP != 50)
3414       GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
3415   }
3416 
3417   if (Opts.OpenMPThreadSubscription)
3418     GenerateArg(Args, OPT_fopenmp_assume_threads_oversubscription, SA);
3419 
3420   if (Opts.OpenMPTeamSubscription)
3421     GenerateArg(Args, OPT_fopenmp_assume_teams_oversubscription, SA);
3422 
3423   if (Opts.OpenMPTargetDebug != 0)
3424     GenerateArg(Args, OPT_fopenmp_target_debug_EQ,
3425                 Twine(Opts.OpenMPTargetDebug), SA);
3426 
3427   if (Opts.OpenMPCUDANumSMs != 0)
3428     GenerateArg(Args, OPT_fopenmp_cuda_number_of_sm_EQ,
3429                 Twine(Opts.OpenMPCUDANumSMs), SA);
3430 
3431   if (Opts.OpenMPCUDABlocksPerSM != 0)
3432     GenerateArg(Args, OPT_fopenmp_cuda_blocks_per_sm_EQ,
3433                 Twine(Opts.OpenMPCUDABlocksPerSM), SA);
3434 
3435   if (Opts.OpenMPCUDAReductionBufNum != 1024)
3436     GenerateArg(Args, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3437                 Twine(Opts.OpenMPCUDAReductionBufNum), SA);
3438 
3439   if (!Opts.OMPTargetTriples.empty()) {
3440     std::string Targets;
3441     llvm::raw_string_ostream OS(Targets);
3442     llvm::interleave(
3443         Opts.OMPTargetTriples, OS,
3444         [&OS](const llvm::Triple &T) { OS << T.str(); }, ",");
3445     GenerateArg(Args, OPT_fopenmp_targets_EQ, OS.str(), SA);
3446   }
3447 
3448   if (!Opts.OMPHostIRFile.empty())
3449     GenerateArg(Args, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile, SA);
3450 
3451   if (Opts.OpenMPCUDAMode)
3452     GenerateArg(Args, OPT_fopenmp_cuda_mode, SA);
3453 
3454   // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are
3455   // generated from CodeGenOptions.
3456 
3457   if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast)
3458     GenerateArg(Args, OPT_ffp_contract, "fast", SA);
3459   else if (Opts.DefaultFPContractMode == LangOptions::FPM_On)
3460     GenerateArg(Args, OPT_ffp_contract, "on", SA);
3461   else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off)
3462     GenerateArg(Args, OPT_ffp_contract, "off", SA);
3463   else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas)
3464     GenerateArg(Args, OPT_ffp_contract, "fast-honor-pragmas", SA);
3465 
3466   for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3467     GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
3468 
3469   // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'.
3470   for (const std::string &F : Opts.NoSanitizeFiles)
3471     GenerateArg(Args, OPT_fsanitize_ignorelist_EQ, F, SA);
3472 
3473   if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver3_8)
3474     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "3.8", SA);
3475   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver4)
3476     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "4.0", SA);
3477   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver6)
3478     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "6.0", SA);
3479   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver7)
3480     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "7.0", SA);
3481   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver9)
3482     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "9.0", SA);
3483   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver11)
3484     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "11.0", SA);
3485   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver12)
3486     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "12.0", SA);
3487   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver14)
3488     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "14.0", SA);
3489   else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver15)
3490     GenerateArg(Args, OPT_fclang_abi_compat_EQ, "15.0", SA);
3491 
3492   if (Opts.getSignReturnAddressScope() ==
3493       LangOptions::SignReturnAddressScopeKind::All)
3494     GenerateArg(Args, OPT_msign_return_address_EQ, "all", SA);
3495   else if (Opts.getSignReturnAddressScope() ==
3496            LangOptions::SignReturnAddressScopeKind::NonLeaf)
3497     GenerateArg(Args, OPT_msign_return_address_EQ, "non-leaf", SA);
3498 
3499   if (Opts.getSignReturnAddressKey() ==
3500       LangOptions::SignReturnAddressKeyKind::BKey)
3501     GenerateArg(Args, OPT_msign_return_address_key_EQ, "b_key", SA);
3502 
3503   if (Opts.CXXABI)
3504     GenerateArg(Args, OPT_fcxx_abi_EQ, TargetCXXABI::getSpelling(*Opts.CXXABI),
3505                 SA);
3506 
3507   if (Opts.RelativeCXXABIVTables)
3508     GenerateArg(Args, OPT_fexperimental_relative_cxx_abi_vtables, SA);
3509   else
3510     GenerateArg(Args, OPT_fno_experimental_relative_cxx_abi_vtables, SA);
3511 
3512   if (Opts.UseTargetPathSeparator)
3513     GenerateArg(Args, OPT_ffile_reproducible, SA);
3514   else
3515     GenerateArg(Args, OPT_fno_file_reproducible, SA);
3516 
3517   for (const auto &MP : Opts.MacroPrefixMap)
3518     GenerateArg(Args, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second, SA);
3519 
3520   if (!Opts.RandstructSeed.empty())
3521     GenerateArg(Args, OPT_frandomize_layout_seed_EQ, Opts.RandstructSeed, SA);
3522 }
3523 
3524 bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
3525                                        InputKind IK, const llvm::Triple &T,
3526                                        std::vector<std::string> &Includes,
3527                                        DiagnosticsEngine &Diags) {
3528   unsigned NumErrorsBefore = Diags.getNumErrors();
3529 
3530   if (IK.getFormat() == InputKind::Precompiled ||
3531       IK.getLanguage() == Language::LLVM_IR) {
3532     // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3533     // PassManager in BackendUtil.cpp. They need to be initialized no matter
3534     // what the input type is.
3535     if (Args.hasArg(OPT_fobjc_arc))
3536       Opts.ObjCAutoRefCount = 1;
3537     // PICLevel and PIELevel are needed during code generation and this should
3538     // be set regardless of the input type.
3539     Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3540     Opts.PIE = Args.hasArg(OPT_pic_is_pie);
3541     parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3542                         Diags, Opts.Sanitize);
3543 
3544     return Diags.getNumErrors() == NumErrorsBefore;
3545   }
3546 
3547   // Other LangOpts are only initialized when the input is not AST or LLVM IR.
3548   // FIXME: Should we really be parsing this for an Language::Asm input?
3549 
3550   // FIXME: Cleanup per-file based stuff.
3551   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
3552   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
3553     LangStd = LangStandard::getLangKind(A->getValue());
3554     if (LangStd == LangStandard::lang_unspecified) {
3555       Diags.Report(diag::err_drv_invalid_value)
3556         << A->getAsString(Args) << A->getValue();
3557       // Report supported standards with short description.
3558       for (unsigned KindValue = 0;
3559            KindValue != LangStandard::lang_unspecified;
3560            ++KindValue) {
3561         const LangStandard &Std = LangStandard::getLangStandardForKind(
3562           static_cast<LangStandard::Kind>(KindValue));
3563         if (IsInputCompatibleWithStandard(IK, Std)) {
3564           auto Diag = Diags.Report(diag::note_drv_use_standard);
3565           Diag << Std.getName() << Std.getDescription();
3566           unsigned NumAliases = 0;
3567 #define LANGSTANDARD(id, name, lang, desc, features)
3568 #define LANGSTANDARD_ALIAS(id, alias) \
3569           if (KindValue == LangStandard::lang_##id) ++NumAliases;
3570 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3571 #include "clang/Basic/LangStandards.def"
3572           Diag << NumAliases;
3573 #define LANGSTANDARD(id, name, lang, desc, features)
3574 #define LANGSTANDARD_ALIAS(id, alias) \
3575           if (KindValue == LangStandard::lang_##id) Diag << alias;
3576 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3577 #include "clang/Basic/LangStandards.def"
3578         }
3579       }
3580     } else {
3581       // Valid standard, check to make sure language and standard are
3582       // compatible.
3583       const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
3584       if (!IsInputCompatibleWithStandard(IK, Std)) {
3585         Diags.Report(diag::err_drv_argument_not_allowed_with)
3586           << A->getAsString(Args) << GetInputKindName(IK);
3587       }
3588     }
3589   }
3590 
3591   // -cl-std only applies for OpenCL language standards.
3592   // Override the -std option in this case.
3593   if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
3594     LangStandard::Kind OpenCLLangStd
3595       = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
3596         .Cases("cl", "CL", LangStandard::lang_opencl10)
3597         .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10)
3598         .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
3599         .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
3600         .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
3601         .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
3602         .Cases("clc++", "CLC++", LangStandard::lang_openclcpp10)
3603         .Cases("clc++1.0", "CLC++1.0", LangStandard::lang_openclcpp10)
3604         .Cases("clc++2021", "CLC++2021", LangStandard::lang_openclcpp2021)
3605         .Default(LangStandard::lang_unspecified);
3606 
3607     if (OpenCLLangStd == LangStandard::lang_unspecified) {
3608       Diags.Report(diag::err_drv_invalid_value)
3609         << A->getAsString(Args) << A->getValue();
3610     }
3611     else
3612       LangStd = OpenCLLangStd;
3613   }
3614 
3615   // These need to be parsed now. They are used to set OpenCL defaults.
3616   Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
3617   Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
3618 
3619   LangOptions::setLangDefaults(Opts, IK.getLanguage(), T, Includes, LangStd);
3620 
3621   // The key paths of codegen options defined in Options.td start with
3622   // "LangOpts->". Let's provide the expected variable name and type.
3623   LangOptions *LangOpts = &Opts;
3624 
3625 #define LANG_OPTION_WITH_MARSHALLING(...)                                      \
3626   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3627 #include "clang/Driver/Options.inc"
3628 #undef LANG_OPTION_WITH_MARSHALLING
3629 
3630   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3631     StringRef Name = A->getValue();
3632     if (Name == "full" || Name == "branch") {
3633       Opts.CFProtectionBranch = 1;
3634     }
3635   }
3636 
3637   if ((Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) &&
3638       !Args.hasArg(OPT_sycl_std_EQ)) {
3639     // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to
3640     // provide -sycl-std=, we want to default it to whatever the default SYCL
3641     // version is. I could not find a way to express this with the options
3642     // tablegen because we still want this value to be SYCL_None when the user
3643     // is not in device or host mode.
3644     Opts.setSYCLVersion(LangOptions::SYCL_Default);
3645   }
3646 
3647   if (Opts.ObjC) {
3648     if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
3649       StringRef value = arg->getValue();
3650       if (Opts.ObjCRuntime.tryParse(value))
3651         Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
3652     }
3653 
3654     if (Args.hasArg(OPT_fobjc_gc_only))
3655       Opts.setGC(LangOptions::GCOnly);
3656     else if (Args.hasArg(OPT_fobjc_gc))
3657       Opts.setGC(LangOptions::HybridGC);
3658     else if (Args.hasArg(OPT_fobjc_arc)) {
3659       Opts.ObjCAutoRefCount = 1;
3660       if (!Opts.ObjCRuntime.allowsARC())
3661         Diags.Report(diag::err_arc_unsupported_on_runtime);
3662     }
3663 
3664     // ObjCWeakRuntime tracks whether the runtime supports __weak, not
3665     // whether the feature is actually enabled.  This is predominantly
3666     // determined by -fobjc-runtime, but we allow it to be overridden
3667     // from the command line for testing purposes.
3668     if (Args.hasArg(OPT_fobjc_runtime_has_weak))
3669       Opts.ObjCWeakRuntime = 1;
3670     else
3671       Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
3672 
3673     // ObjCWeak determines whether __weak is actually enabled.
3674     // Note that we allow -fno-objc-weak to disable this even in ARC mode.
3675     if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
3676       if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
3677         assert(!Opts.ObjCWeak);
3678       } else if (Opts.getGC() != LangOptions::NonGC) {
3679         Diags.Report(diag::err_objc_weak_with_gc);
3680       } else if (!Opts.ObjCWeakRuntime) {
3681         Diags.Report(diag::err_objc_weak_unsupported);
3682       } else {
3683         Opts.ObjCWeak = 1;
3684       }
3685     } else if (Opts.ObjCAutoRefCount) {
3686       Opts.ObjCWeak = Opts.ObjCWeakRuntime;
3687     }
3688 
3689     if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
3690       Opts.ObjCSubscriptingLegacyRuntime =
3691         (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
3692   }
3693 
3694   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
3695     // Check that the version has 1 to 3 components and the minor and patch
3696     // versions fit in two decimal digits.
3697     VersionTuple GNUCVer;
3698     bool Invalid = GNUCVer.tryParse(A->getValue());
3699     unsigned Major = GNUCVer.getMajor();
3700     unsigned Minor = GNUCVer.getMinor().value_or(0);
3701     unsigned Patch = GNUCVer.getSubminor().value_or(0);
3702     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
3703       Diags.Report(diag::err_drv_invalid_value)
3704           << A->getAsString(Args) << A->getValue();
3705     }
3706     Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
3707   }
3708 
3709   if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility)))
3710     Opts.IgnoreXCOFFVisibility = 1;
3711 
3712   if (Args.hasArg(OPT_ftrapv)) {
3713     Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
3714     // Set the handler, if one is specified.
3715     Opts.OverflowHandler =
3716         std::string(Args.getLastArgValue(OPT_ftrapv_handler));
3717   }
3718   else if (Args.hasArg(OPT_fwrapv))
3719     Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
3720 
3721   Opts.MSCompatibilityVersion = 0;
3722   if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
3723     VersionTuple VT;
3724     if (VT.tryParse(A->getValue()))
3725       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
3726                                                 << A->getValue();
3727     Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
3728                                   VT.getMinor().value_or(0) * 100000 +
3729                                   VT.getSubminor().value_or(0);
3730   }
3731 
3732   // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
3733   // is specified, or -std is set to a conforming mode.
3734   // Trigraphs are disabled by default in c++1z onwards.
3735   // For z/OS, trigraphs are enabled by default (without regard to the above).
3736   Opts.Trigraphs =
3737       (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS();
3738   Opts.Trigraphs =
3739       Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
3740 
3741   Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
3742     && Opts.OpenCLVersion == 200);
3743 
3744   Opts.ConvergentFunctions = Args.hasArg(OPT_fconvergent_functions) ||
3745                              Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
3746                              Opts.SYCLIsDevice;
3747 
3748   Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
3749   if (!Opts.NoBuiltin)
3750     getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
3751   if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
3752     if (A->getOption().matches(options::OPT_mlong_double_64))
3753       Opts.LongDoubleSize = 64;
3754     else if (A->getOption().matches(options::OPT_mlong_double_80))
3755       Opts.LongDoubleSize = 80;
3756     else if (A->getOption().matches(options::OPT_mlong_double_128))
3757       Opts.LongDoubleSize = 128;
3758     else
3759       Opts.LongDoubleSize = 0;
3760   }
3761   if (Opts.FastRelaxedMath || Opts.CLUnsafeMath)
3762     Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3763 
3764   llvm::sort(Opts.ModuleFeatures);
3765 
3766   // -mrtd option
3767   if (Arg *A = Args.getLastArg(OPT_mrtd)) {
3768     if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
3769       Diags.Report(diag::err_drv_argument_not_allowed_with)
3770           << A->getSpelling() << "-fdefault-calling-conv";
3771     else {
3772       if (T.getArch() != llvm::Triple::x86)
3773         Diags.Report(diag::err_drv_argument_not_allowed_with)
3774             << A->getSpelling() << T.getTriple();
3775       else
3776         Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
3777     }
3778   }
3779 
3780   // Check if -fopenmp is specified and set default version to 5.0.
3781   Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 50 : 0;
3782   // Check if -fopenmp-simd is specified.
3783   bool IsSimdSpecified =
3784       Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
3785                    /*Default=*/false);
3786   Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
3787   Opts.OpenMPUseTLS =
3788       Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
3789   Opts.OpenMPIsDevice =
3790       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
3791   Opts.OpenMPIRBuilder =
3792       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
3793   bool IsTargetSpecified =
3794       Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
3795 
3796   Opts.ConvergentFunctions = Opts.ConvergentFunctions || Opts.OpenMPIsDevice;
3797 
3798   if (Opts.OpenMP || Opts.OpenMPSimd) {
3799     if (int Version = getLastArgIntValue(
3800             Args, OPT_fopenmp_version_EQ,
3801             (IsSimdSpecified || IsTargetSpecified) ? 50 : Opts.OpenMP, Diags))
3802       Opts.OpenMP = Version;
3803     // Provide diagnostic when a given target is not expected to be an OpenMP
3804     // device or host.
3805     if (!Opts.OpenMPIsDevice) {
3806       switch (T.getArch()) {
3807       default:
3808         break;
3809       // Add unsupported host targets here:
3810       case llvm::Triple::nvptx:
3811       case llvm::Triple::nvptx64:
3812         Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
3813         break;
3814       }
3815     }
3816   }
3817 
3818   // Set the flag to prevent the implementation from emitting device exception
3819   // handling code for those requiring so.
3820   if ((Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN())) ||
3821       Opts.OpenCLCPlusPlus) {
3822 
3823     Opts.Exceptions = 0;
3824     Opts.CXXExceptions = 0;
3825   }
3826   if (Opts.OpenMPIsDevice && T.isNVPTX()) {
3827     Opts.OpenMPCUDANumSMs =
3828         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
3829                            Opts.OpenMPCUDANumSMs, Diags);
3830     Opts.OpenMPCUDABlocksPerSM =
3831         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
3832                            Opts.OpenMPCUDABlocksPerSM, Diags);
3833     Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
3834         Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3835         Opts.OpenMPCUDAReductionBufNum, Diags);
3836   }
3837 
3838   // Set the value of the debugging flag used in the new offloading device RTL.
3839   // Set either by a specific value or to a default if not specified.
3840   if (Opts.OpenMPIsDevice && (Args.hasArg(OPT_fopenmp_target_debug) ||
3841                               Args.hasArg(OPT_fopenmp_target_debug_EQ))) {
3842     Opts.OpenMPTargetDebug = getLastArgIntValue(
3843         Args, OPT_fopenmp_target_debug_EQ, Opts.OpenMPTargetDebug, Diags);
3844     if (!Opts.OpenMPTargetDebug && Args.hasArg(OPT_fopenmp_target_debug))
3845       Opts.OpenMPTargetDebug = 1;
3846   }
3847 
3848   if (Opts.OpenMPIsDevice) {
3849     if (Args.hasArg(OPT_fopenmp_assume_teams_oversubscription))
3850       Opts.OpenMPTeamSubscription = true;
3851     if (Args.hasArg(OPT_fopenmp_assume_threads_oversubscription))
3852       Opts.OpenMPThreadSubscription = true;
3853   }
3854 
3855   // Get the OpenMP target triples if any.
3856   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
3857     enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
3858     auto getArchPtrSize = [](const llvm::Triple &T) {
3859       if (T.isArch16Bit())
3860         return Arch16Bit;
3861       if (T.isArch32Bit())
3862         return Arch32Bit;
3863       assert(T.isArch64Bit() && "Expected 64-bit architecture");
3864       return Arch64Bit;
3865     };
3866 
3867     for (unsigned i = 0; i < A->getNumValues(); ++i) {
3868       llvm::Triple TT(A->getValue(i));
3869 
3870       if (TT.getArch() == llvm::Triple::UnknownArch ||
3871           !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
3872             TT.getArch() == llvm::Triple::nvptx ||
3873             TT.getArch() == llvm::Triple::nvptx64 ||
3874             TT.getArch() == llvm::Triple::amdgcn ||
3875             TT.getArch() == llvm::Triple::x86 ||
3876             TT.getArch() == llvm::Triple::x86_64))
3877         Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
3878       else if (getArchPtrSize(T) != getArchPtrSize(TT))
3879         Diags.Report(diag::err_drv_incompatible_omp_arch)
3880             << A->getValue(i) << T.str();
3881       else
3882         Opts.OMPTargetTriples.push_back(TT);
3883     }
3884   }
3885 
3886   // Get OpenMP host file path if any and report if a non existent file is
3887   // found
3888   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
3889     Opts.OMPHostIRFile = A->getValue();
3890     if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
3891       Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
3892           << Opts.OMPHostIRFile;
3893   }
3894 
3895   // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
3896   Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
3897                         Args.hasArg(options::OPT_fopenmp_cuda_mode);
3898 
3899   // FIXME: Eliminate this dependency.
3900   unsigned Opt = getOptimizationLevel(Args, IK, Diags),
3901        OptSize = getOptimizationLevelSize(Args);
3902   Opts.Optimize = Opt != 0;
3903   Opts.OptimizeSize = OptSize != 0;
3904 
3905   // This is the __NO_INLINE__ define, which just depends on things like the
3906   // optimization level and -fno-inline, not actually whether the backend has
3907   // inlining enabled.
3908   Opts.NoInlineDefine = !Opts.Optimize;
3909   if (Arg *InlineArg = Args.getLastArg(
3910           options::OPT_finline_functions, options::OPT_finline_hint_functions,
3911           options::OPT_fno_inline_functions, options::OPT_fno_inline))
3912     if (InlineArg->getOption().matches(options::OPT_fno_inline))
3913       Opts.NoInlineDefine = true;
3914 
3915   if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
3916     StringRef Val = A->getValue();
3917     if (Val == "fast")
3918       Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3919     else if (Val == "on")
3920       Opts.setDefaultFPContractMode(LangOptions::FPM_On);
3921     else if (Val == "off")
3922       Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
3923     else if (Val == "fast-honor-pragmas")
3924       Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
3925     else
3926       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3927   }
3928 
3929   // Parse -fsanitize= arguments.
3930   parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3931                       Diags, Opts.Sanitize);
3932   Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ);
3933   std::vector<std::string> systemIgnorelists =
3934       Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ);
3935   Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(),
3936                               systemIgnorelists.begin(),
3937                               systemIgnorelists.end());
3938 
3939   if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
3940     Opts.setClangABICompat(LangOptions::ClangABI::Latest);
3941 
3942     StringRef Ver = A->getValue();
3943     std::pair<StringRef, StringRef> VerParts = Ver.split('.');
3944     unsigned Major, Minor = 0;
3945 
3946     // Check the version number is valid: either 3.x (0 <= x <= 9) or
3947     // y or y.0 (4 <= y <= current version).
3948     if (!VerParts.first.startswith("0") &&
3949         !VerParts.first.getAsInteger(10, Major) &&
3950         3 <= Major && Major <= CLANG_VERSION_MAJOR &&
3951         (Major == 3 ? VerParts.second.size() == 1 &&
3952                       !VerParts.second.getAsInteger(10, Minor)
3953                     : VerParts.first.size() == Ver.size() ||
3954                       VerParts.second == "0")) {
3955       // Got a valid version number.
3956       if (Major == 3 && Minor <= 8)
3957         Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
3958       else if (Major <= 4)
3959         Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
3960       else if (Major <= 6)
3961         Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
3962       else if (Major <= 7)
3963         Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
3964       else if (Major <= 9)
3965         Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
3966       else if (Major <= 11)
3967         Opts.setClangABICompat(LangOptions::ClangABI::Ver11);
3968       else if (Major <= 12)
3969         Opts.setClangABICompat(LangOptions::ClangABI::Ver12);
3970       else if (Major <= 14)
3971         Opts.setClangABICompat(LangOptions::ClangABI::Ver14);
3972       else if (Major <= 15)
3973         Opts.setClangABICompat(LangOptions::ClangABI::Ver15);
3974     } else if (Ver != "latest") {
3975       Diags.Report(diag::err_drv_invalid_value)
3976           << A->getAsString(Args) << A->getValue();
3977     }
3978   }
3979 
3980   if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
3981     StringRef SignScope = A->getValue();
3982 
3983     if (SignScope.equals_insensitive("none"))
3984       Opts.setSignReturnAddressScope(
3985           LangOptions::SignReturnAddressScopeKind::None);
3986     else if (SignScope.equals_insensitive("all"))
3987       Opts.setSignReturnAddressScope(
3988           LangOptions::SignReturnAddressScopeKind::All);
3989     else if (SignScope.equals_insensitive("non-leaf"))
3990       Opts.setSignReturnAddressScope(
3991           LangOptions::SignReturnAddressScopeKind::NonLeaf);
3992     else
3993       Diags.Report(diag::err_drv_invalid_value)
3994           << A->getAsString(Args) << SignScope;
3995 
3996     if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
3997       StringRef SignKey = A->getValue();
3998       if (!SignScope.empty() && !SignKey.empty()) {
3999         if (SignKey.equals_insensitive("a_key"))
4000           Opts.setSignReturnAddressKey(
4001               LangOptions::SignReturnAddressKeyKind::AKey);
4002         else if (SignKey.equals_insensitive("b_key"))
4003           Opts.setSignReturnAddressKey(
4004               LangOptions::SignReturnAddressKeyKind::BKey);
4005         else
4006           Diags.Report(diag::err_drv_invalid_value)
4007               << A->getAsString(Args) << SignKey;
4008       }
4009     }
4010   }
4011 
4012   // The value can be empty, which indicates the system default should be used.
4013   StringRef CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ);
4014   if (!CXXABI.empty()) {
4015     if (!TargetCXXABI::isABI(CXXABI)) {
4016       Diags.Report(diag::err_invalid_cxx_abi) << CXXABI;
4017     } else {
4018       auto Kind = TargetCXXABI::getKind(CXXABI);
4019       if (!TargetCXXABI::isSupportedCXXABI(T, Kind))
4020         Diags.Report(diag::err_unsupported_cxx_abi) << CXXABI << T.str();
4021       else
4022         Opts.CXXABI = Kind;
4023     }
4024   }
4025 
4026   Opts.RelativeCXXABIVTables =
4027       Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables,
4028                    options::OPT_fno_experimental_relative_cxx_abi_vtables,
4029                    TargetCXXABI::usesRelativeVTables(T));
4030 
4031   for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
4032     auto Split = StringRef(A).split('=');
4033     Opts.MacroPrefixMap.insert(
4034         {std::string(Split.first), std::string(Split.second)});
4035   }
4036 
4037   Opts.UseTargetPathSeparator =
4038       !Args.getLastArg(OPT_fno_file_reproducible) &&
4039       (Args.getLastArg(OPT_ffile_compilation_dir_EQ) ||
4040        Args.getLastArg(OPT_fmacro_prefix_map_EQ) ||
4041        Args.getLastArg(OPT_ffile_reproducible));
4042 
4043   // Error if -mvscale-min is unbounded.
4044   if (Arg *A = Args.getLastArg(options::OPT_mvscale_min_EQ)) {
4045     unsigned VScaleMin;
4046     if (StringRef(A->getValue()).getAsInteger(10, VScaleMin) || VScaleMin == 0)
4047       Diags.Report(diag::err_cc1_unbounded_vscale_min);
4048   }
4049 
4050   if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_file_EQ)) {
4051     std::ifstream SeedFile(A->getValue(0));
4052 
4053     if (!SeedFile.is_open())
4054       Diags.Report(diag::err_drv_cannot_open_randomize_layout_seed_file)
4055           << A->getValue(0);
4056 
4057     std::getline(SeedFile, Opts.RandstructSeed);
4058   }
4059 
4060   if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_EQ))
4061     Opts.RandstructSeed = A->getValue(0);
4062 
4063   // Validate options for HLSL
4064   if (Opts.HLSL) {
4065     bool SupportedTarget = T.getArch() == llvm::Triple::dxil &&
4066                            T.getOS() == llvm::Triple::ShaderModel;
4067     if (!SupportedTarget)
4068       Diags.Report(diag::err_drv_hlsl_unsupported_target) << T.str();
4069   }
4070 
4071   return Diags.getNumErrors() == NumErrorsBefore;
4072 }
4073 
4074 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
4075   switch (Action) {
4076   case frontend::ASTDeclList:
4077   case frontend::ASTDump:
4078   case frontend::ASTPrint:
4079   case frontend::ASTView:
4080   case frontend::EmitAssembly:
4081   case frontend::EmitBC:
4082   case frontend::EmitHTML:
4083   case frontend::EmitLLVM:
4084   case frontend::EmitLLVMOnly:
4085   case frontend::EmitCodeGenOnly:
4086   case frontend::EmitObj:
4087   case frontend::ExtractAPI:
4088   case frontend::FixIt:
4089   case frontend::GenerateModule:
4090   case frontend::GenerateModuleInterface:
4091   case frontend::GenerateHeaderUnit:
4092   case frontend::GeneratePCH:
4093   case frontend::GenerateInterfaceStubs:
4094   case frontend::ParseSyntaxOnly:
4095   case frontend::ModuleFileInfo:
4096   case frontend::VerifyPCH:
4097   case frontend::PluginAction:
4098   case frontend::RewriteObjC:
4099   case frontend::RewriteTest:
4100   case frontend::RunAnalysis:
4101   case frontend::TemplightDump:
4102   case frontend::MigrateSource:
4103     return false;
4104 
4105   case frontend::DumpCompilerOptions:
4106   case frontend::DumpRawTokens:
4107   case frontend::DumpTokens:
4108   case frontend::InitOnly:
4109   case frontend::PrintPreamble:
4110   case frontend::PrintPreprocessedInput:
4111   case frontend::RewriteMacros:
4112   case frontend::RunPreprocessorOnly:
4113   case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
4114     return true;
4115   }
4116   llvm_unreachable("invalid frontend action");
4117 }
4118 
4119 static void GeneratePreprocessorArgs(PreprocessorOptions &Opts,
4120                                      SmallVectorImpl<const char *> &Args,
4121                                      CompilerInvocation::StringAllocator SA,
4122                                      const LangOptions &LangOpts,
4123                                      const FrontendOptions &FrontendOpts,
4124                                      const CodeGenOptions &CodeGenOpts) {
4125   PreprocessorOptions *PreprocessorOpts = &Opts;
4126 
4127 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...)                              \
4128   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
4129 #include "clang/Driver/Options.inc"
4130 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4131 
4132   if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
4133     GenerateArg(Args, OPT_pch_through_hdrstop_use, SA);
4134 
4135   for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
4136     GenerateArg(Args, OPT_error_on_deserialized_pch_decl, D, SA);
4137 
4138   if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
4139     GenerateArg(Args, OPT_preamble_bytes_EQ,
4140                 Twine(Opts.PrecompiledPreambleBytes.first) + "," +
4141                     (Opts.PrecompiledPreambleBytes.second ? "1" : "0"),
4142                 SA);
4143 
4144   for (const auto &M : Opts.Macros) {
4145     // Don't generate __CET__ macro definitions. They are implied by the
4146     // -fcf-protection option that is generated elsewhere.
4147     if (M.first == "__CET__=1" && !M.second &&
4148         !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
4149       continue;
4150     if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
4151         !CodeGenOpts.CFProtectionBranch)
4152       continue;
4153     if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
4154         CodeGenOpts.CFProtectionBranch)
4155       continue;
4156 
4157     GenerateArg(Args, M.second ? OPT_U : OPT_D, M.first, SA);
4158   }
4159 
4160   for (const auto &I : Opts.Includes) {
4161     // Don't generate OpenCL includes. They are implied by other flags that are
4162     // generated elsewhere.
4163     if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
4164         ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
4165          I == "opencl-c.h"))
4166       continue;
4167     // Don't generate HLSL includes. They are implied by other flags that are
4168     // generated elsewhere.
4169     if (LangOpts.HLSL && I == "hlsl.h")
4170       continue;
4171 
4172     GenerateArg(Args, OPT_include, I, SA);
4173   }
4174 
4175   for (const auto &CI : Opts.ChainedIncludes)
4176     GenerateArg(Args, OPT_chain_include, CI, SA);
4177 
4178   for (const auto &RF : Opts.RemappedFiles)
4179     GenerateArg(Args, OPT_remap_file, RF.first + ";" + RF.second, SA);
4180 
4181   if (Opts.SourceDateEpoch)
4182     GenerateArg(Args, OPT_source_date_epoch, Twine(*Opts.SourceDateEpoch), SA);
4183 
4184   // Don't handle LexEditorPlaceholders. It is implied by the action that is
4185   // generated elsewhere.
4186 }
4187 
4188 static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
4189                                   DiagnosticsEngine &Diags,
4190                                   frontend::ActionKind Action,
4191                                   const FrontendOptions &FrontendOpts) {
4192   unsigned NumErrorsBefore = Diags.getNumErrors();
4193 
4194   PreprocessorOptions *PreprocessorOpts = &Opts;
4195 
4196 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...)                              \
4197   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4198 #include "clang/Driver/Options.inc"
4199 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4200 
4201   Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
4202                         Args.hasArg(OPT_pch_through_hdrstop_use);
4203 
4204   for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
4205     Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
4206 
4207   if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
4208     StringRef Value(A->getValue());
4209     size_t Comma = Value.find(',');
4210     unsigned Bytes = 0;
4211     unsigned EndOfLine = 0;
4212 
4213     if (Comma == StringRef::npos ||
4214         Value.substr(0, Comma).getAsInteger(10, Bytes) ||
4215         Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
4216       Diags.Report(diag::err_drv_preamble_format);
4217     else {
4218       Opts.PrecompiledPreambleBytes.first = Bytes;
4219       Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
4220     }
4221   }
4222 
4223   // Add the __CET__ macro if a CFProtection option is set.
4224   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
4225     StringRef Name = A->getValue();
4226     if (Name == "branch")
4227       Opts.addMacroDef("__CET__=1");
4228     else if (Name == "return")
4229       Opts.addMacroDef("__CET__=2");
4230     else if (Name == "full")
4231       Opts.addMacroDef("__CET__=3");
4232   }
4233 
4234   // Add macros from the command line.
4235   for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
4236     if (A->getOption().matches(OPT_D))
4237       Opts.addMacroDef(A->getValue());
4238     else
4239       Opts.addMacroUndef(A->getValue());
4240   }
4241 
4242   // Add the ordered list of -includes.
4243   for (const auto *A : Args.filtered(OPT_include))
4244     Opts.Includes.emplace_back(A->getValue());
4245 
4246   for (const auto *A : Args.filtered(OPT_chain_include))
4247     Opts.ChainedIncludes.emplace_back(A->getValue());
4248 
4249   for (const auto *A : Args.filtered(OPT_remap_file)) {
4250     std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
4251 
4252     if (Split.second.empty()) {
4253       Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
4254       continue;
4255     }
4256 
4257     Opts.addRemappedFile(Split.first, Split.second);
4258   }
4259 
4260   if (const Arg *A = Args.getLastArg(OPT_source_date_epoch)) {
4261     StringRef Epoch = A->getValue();
4262     // SOURCE_DATE_EPOCH, if specified, must be a non-negative decimal integer.
4263     // On time64 systems, pick 253402300799 (the UNIX timestamp of
4264     // 9999-12-31T23:59:59Z) as the upper bound.
4265     const uint64_t MaxTimestamp =
4266         std::min<uint64_t>(std::numeric_limits<time_t>::max(), 253402300799);
4267     uint64_t V;
4268     if (Epoch.getAsInteger(10, V) || V > MaxTimestamp) {
4269       Diags.Report(diag::err_fe_invalid_source_date_epoch)
4270           << Epoch << MaxTimestamp;
4271     } else {
4272       Opts.SourceDateEpoch = V;
4273     }
4274   }
4275 
4276   // Always avoid lexing editor placeholders when we're just running the
4277   // preprocessor as we never want to emit the
4278   // "editor placeholder in source file" error in PP only mode.
4279   if (isStrictlyPreprocessorAction(Action))
4280     Opts.LexEditorPlaceholders = false;
4281 
4282   return Diags.getNumErrors() == NumErrorsBefore;
4283 }
4284 
4285 static void GeneratePreprocessorOutputArgs(
4286     const PreprocessorOutputOptions &Opts, SmallVectorImpl<const char *> &Args,
4287     CompilerInvocation::StringAllocator SA, frontend::ActionKind Action) {
4288   const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4289 
4290 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...)                       \
4291   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
4292 #include "clang/Driver/Options.inc"
4293 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4294 
4295   bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
4296   if (Generate_dM)
4297     GenerateArg(Args, OPT_dM, SA);
4298   if (!Generate_dM && Opts.ShowMacros)
4299     GenerateArg(Args, OPT_dD, SA);
4300   if (Opts.DirectivesOnly)
4301     GenerateArg(Args, OPT_fdirectives_only, SA);
4302 }
4303 
4304 static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
4305                                         ArgList &Args, DiagnosticsEngine &Diags,
4306                                         frontend::ActionKind Action) {
4307   unsigned NumErrorsBefore = Diags.getNumErrors();
4308 
4309   PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4310 
4311 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...)                       \
4312   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4313 #include "clang/Driver/Options.inc"
4314 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4315 
4316   Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
4317   Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
4318   Opts.DirectivesOnly = Args.hasArg(OPT_fdirectives_only);
4319 
4320   return Diags.getNumErrors() == NumErrorsBefore;
4321 }
4322 
4323 static void GenerateTargetArgs(const TargetOptions &Opts,
4324                                SmallVectorImpl<const char *> &Args,
4325                                CompilerInvocation::StringAllocator SA) {
4326   const TargetOptions *TargetOpts = &Opts;
4327 #define TARGET_OPTION_WITH_MARSHALLING(...)                                    \
4328   GENERATE_OPTION_WITH_MARSHALLING(Args, SA, __VA_ARGS__)
4329 #include "clang/Driver/Options.inc"
4330 #undef TARGET_OPTION_WITH_MARSHALLING
4331 
4332   if (!Opts.SDKVersion.empty())
4333     GenerateArg(Args, OPT_target_sdk_version_EQ, Opts.SDKVersion.getAsString(),
4334                 SA);
4335   if (!Opts.DarwinTargetVariantSDKVersion.empty())
4336     GenerateArg(Args, OPT_darwin_target_variant_sdk_version_EQ,
4337                 Opts.DarwinTargetVariantSDKVersion.getAsString(), SA);
4338 }
4339 
4340 static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
4341                             DiagnosticsEngine &Diags) {
4342   unsigned NumErrorsBefore = Diags.getNumErrors();
4343 
4344   TargetOptions *TargetOpts = &Opts;
4345 
4346 #define TARGET_OPTION_WITH_MARSHALLING(...)                                    \
4347   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4348 #include "clang/Driver/Options.inc"
4349 #undef TARGET_OPTION_WITH_MARSHALLING
4350 
4351   if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
4352     llvm::VersionTuple Version;
4353     if (Version.tryParse(A->getValue()))
4354       Diags.Report(diag::err_drv_invalid_value)
4355           << A->getAsString(Args) << A->getValue();
4356     else
4357       Opts.SDKVersion = Version;
4358   }
4359   if (Arg *A =
4360           Args.getLastArg(options::OPT_darwin_target_variant_sdk_version_EQ)) {
4361     llvm::VersionTuple Version;
4362     if (Version.tryParse(A->getValue()))
4363       Diags.Report(diag::err_drv_invalid_value)
4364           << A->getAsString(Args) << A->getValue();
4365     else
4366       Opts.DarwinTargetVariantSDKVersion = Version;
4367   }
4368 
4369   return Diags.getNumErrors() == NumErrorsBefore;
4370 }
4371 
4372 bool CompilerInvocation::CreateFromArgsImpl(
4373     CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs,
4374     DiagnosticsEngine &Diags, const char *Argv0) {
4375   unsigned NumErrorsBefore = Diags.getNumErrors();
4376 
4377   // Parse the arguments.
4378   const OptTable &Opts = getDriverOptTable();
4379   const unsigned IncludedFlagsBitmask = options::CC1Option;
4380   unsigned MissingArgIndex, MissingArgCount;
4381   InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
4382                                      MissingArgCount, IncludedFlagsBitmask);
4383   LangOptions &LangOpts = *Res.getLangOpts();
4384 
4385   // Check for missing argument error.
4386   if (MissingArgCount)
4387     Diags.Report(diag::err_drv_missing_argument)
4388         << Args.getArgString(MissingArgIndex) << MissingArgCount;
4389 
4390   // Issue errors on unknown arguments.
4391   for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
4392     auto ArgString = A->getAsString(Args);
4393     std::string Nearest;
4394     if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
4395       Diags.Report(diag::err_drv_unknown_argument) << ArgString;
4396     else
4397       Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
4398           << ArgString << Nearest;
4399   }
4400 
4401   ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags);
4402   ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags);
4403   ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
4404   ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
4405                       /*DefaultDiagColor=*/false);
4406   ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile);
4407   // FIXME: We shouldn't have to pass the DashX option around here
4408   InputKind DashX = Res.getFrontendOpts().DashX;
4409   ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
4410   llvm::Triple T(Res.getTargetOpts().Triple);
4411   ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags,
4412                         Res.getFileSystemOpts().WorkingDir);
4413 
4414   ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
4415                 Diags);
4416   if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
4417     LangOpts.ObjCExceptions = 1;
4418 
4419   for (auto Warning : Res.getDiagnosticOpts().Warnings) {
4420     if (Warning == "misexpect" &&
4421         !Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation())) {
4422       Res.getCodeGenOpts().MisExpect = true;
4423     }
4424   }
4425 
4426   if (LangOpts.CUDA) {
4427     // During CUDA device-side compilation, the aux triple is the
4428     // triple used for host compilation.
4429     if (LangOpts.CUDAIsDevice)
4430       Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
4431   }
4432 
4433   // Set the triple of the host for OpenMP device compile.
4434   if (LangOpts.OpenMPIsDevice)
4435     Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
4436 
4437   ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
4438                    Res.getFrontendOpts().OutputFile, LangOpts);
4439 
4440   // FIXME: Override value name discarding when asan or msan is used because the
4441   // backend passes depend on the name of the alloca in order to print out
4442   // names.
4443   Res.getCodeGenOpts().DiscardValueNames &=
4444       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4445       !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
4446       !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
4447       !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
4448 
4449   ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
4450                         Res.getFrontendOpts().ProgramAction,
4451                         Res.getFrontendOpts());
4452   ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, Diags,
4453                               Res.getFrontendOpts().ProgramAction);
4454 
4455   ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args, Diags,
4456                             Res.getFrontendOpts().ProgramAction,
4457                             Res.getPreprocessorOutputOpts().ShowLineMarkers);
4458   if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
4459       Res.getDependencyOutputOpts().Targets.empty())
4460     Diags.Report(diag::err_fe_dependency_file_requires_MT);
4461 
4462   // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
4463   if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
4464       !Res.getLangOpts()->Sanitize.empty()) {
4465     Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
4466     Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
4467   }
4468 
4469   // Store the command-line for using in the CodeView backend.
4470   if (Res.getCodeGenOpts().CodeViewCommandLine) {
4471     Res.getCodeGenOpts().Argv0 = Argv0;
4472     append_range(Res.getCodeGenOpts().CommandLineArgs, CommandLineArgs);
4473   }
4474 
4475   // Set PGOOptions. Need to create a temporary VFS to read the profile
4476   // to determine the PGO type.
4477   if (!Res.getCodeGenOpts().ProfileInstrumentUsePath.empty()) {
4478     auto FS =
4479         createVFSFromOverlayFiles(Res.getHeaderSearchOpts().VFSOverlayFiles,
4480                                   Diags, llvm::vfs::getRealFileSystem());
4481     setPGOUseInstrumentor(Res.getCodeGenOpts(),
4482                           Res.getCodeGenOpts().ProfileInstrumentUsePath, *FS,
4483                           Diags);
4484   }
4485 
4486   FixupInvocation(Res, Diags, Args, DashX);
4487 
4488   return Diags.getNumErrors() == NumErrorsBefore;
4489 }
4490 
4491 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Invocation,
4492                                         ArrayRef<const char *> CommandLineArgs,
4493                                         DiagnosticsEngine &Diags,
4494                                         const char *Argv0) {
4495   CompilerInvocation DummyInvocation;
4496 
4497   return RoundTrip(
4498       [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
4499          DiagnosticsEngine &Diags, const char *Argv0) {
4500         return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
4501       },
4502       [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
4503          StringAllocator SA) {
4504         Args.push_back("-cc1");
4505         Invocation.generateCC1CommandLine(Args, SA);
4506       },
4507       Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
4508 }
4509 
4510 std::string CompilerInvocation::getModuleHash() const {
4511   // FIXME: Consider using SHA1 instead of MD5.
4512   llvm::HashBuilder<llvm::MD5, llvm::support::endianness::native> HBuilder;
4513 
4514   // Note: For QoI reasons, the things we use as a hash here should all be
4515   // dumped via the -module-info flag.
4516 
4517   // Start the signature with the compiler version.
4518   HBuilder.add(getClangFullRepositoryVersion());
4519 
4520   // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
4521   // and getClangFullRepositoryVersion() doesn't include git revision.
4522   HBuilder.add(serialization::VERSION_MAJOR, serialization::VERSION_MINOR);
4523 
4524   // Extend the signature with the language options
4525 #define LANGOPT(Name, Bits, Default, Description) HBuilder.add(LangOpts->Name);
4526 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description)                   \
4527   HBuilder.add(static_cast<unsigned>(LangOpts->get##Name()));
4528 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
4529 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
4530 #include "clang/Basic/LangOptions.def"
4531 
4532   HBuilder.addRange(LangOpts->ModuleFeatures);
4533 
4534   HBuilder.add(LangOpts->ObjCRuntime);
4535   HBuilder.addRange(LangOpts->CommentOpts.BlockCommandNames);
4536 
4537   // Extend the signature with the target options.
4538   HBuilder.add(TargetOpts->Triple, TargetOpts->CPU, TargetOpts->TuneCPU,
4539                TargetOpts->ABI);
4540   HBuilder.addRange(TargetOpts->FeaturesAsWritten);
4541 
4542   // Extend the signature with preprocessor options.
4543   const PreprocessorOptions &ppOpts = getPreprocessorOpts();
4544   HBuilder.add(ppOpts.UsePredefines, ppOpts.DetailedRecord);
4545 
4546   const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
4547   for (const auto &Macro : getPreprocessorOpts().Macros) {
4548     // If we're supposed to ignore this macro for the purposes of modules,
4549     // don't put it into the hash.
4550     if (!hsOpts.ModulesIgnoreMacros.empty()) {
4551       // Check whether we're ignoring this macro.
4552       StringRef MacroDef = Macro.first;
4553       if (hsOpts.ModulesIgnoreMacros.count(
4554               llvm::CachedHashString(MacroDef.split('=').first)))
4555         continue;
4556     }
4557 
4558     HBuilder.add(Macro);
4559   }
4560 
4561   // Extend the signature with the sysroot and other header search options.
4562   HBuilder.add(hsOpts.Sysroot, hsOpts.ModuleFormat, hsOpts.UseDebugInfo,
4563                hsOpts.UseBuiltinIncludes, hsOpts.UseStandardSystemIncludes,
4564                hsOpts.UseStandardCXXIncludes, hsOpts.UseLibcxx,
4565                hsOpts.ModulesValidateDiagnosticOptions);
4566   HBuilder.add(hsOpts.ResourceDir);
4567 
4568   if (hsOpts.ModulesStrictContextHash) {
4569     HBuilder.addRange(hsOpts.SystemHeaderPrefixes);
4570     HBuilder.addRange(hsOpts.UserEntries);
4571 
4572     const DiagnosticOptions &diagOpts = getDiagnosticOpts();
4573 #define DIAGOPT(Name, Bits, Default) HBuilder.add(diagOpts.Name);
4574 #define ENUM_DIAGOPT(Name, Type, Bits, Default)                                \
4575   HBuilder.add(diagOpts.get##Name());
4576 #include "clang/Basic/DiagnosticOptions.def"
4577 #undef DIAGOPT
4578 #undef ENUM_DIAGOPT
4579   }
4580 
4581   // Extend the signature with the user build path.
4582   HBuilder.add(hsOpts.ModuleUserBuildPath);
4583 
4584   // Extend the signature with the module file extensions.
4585   for (const auto &ext : getFrontendOpts().ModuleFileExtensions)
4586     ext->hashExtension(HBuilder);
4587 
4588   // When compiling with -gmodules, also hash -fdebug-prefix-map as it
4589   // affects the debug info in the PCM.
4590   if (getCodeGenOpts().DebugTypeExtRefs)
4591     HBuilder.addRange(getCodeGenOpts().DebugPrefixMap);
4592 
4593   // Extend the signature with the enabled sanitizers, if at least one is
4594   // enabled. Sanitizers which cannot affect AST generation aren't hashed.
4595   SanitizerSet SanHash = LangOpts->Sanitize;
4596   SanHash.clear(getPPTransparentSanitizers());
4597   if (!SanHash.empty())
4598     HBuilder.add(SanHash.Mask);
4599 
4600   llvm::MD5::MD5Result Result;
4601   HBuilder.getHasher().final(Result);
4602   uint64_t Hash = Result.high() ^ Result.low();
4603   return toString(llvm::APInt(64, Hash), 36, /*Signed=*/false);
4604 }
4605 
4606 void CompilerInvocation::generateCC1CommandLine(
4607     SmallVectorImpl<const char *> &Args, StringAllocator SA) const {
4608   llvm::Triple T(TargetOpts->Triple);
4609 
4610   GenerateFileSystemArgs(FileSystemOpts, Args, SA);
4611   GenerateMigratorArgs(MigratorOpts, Args, SA);
4612   GenerateAnalyzerArgs(*AnalyzerOpts, Args, SA);
4613   GenerateDiagnosticArgs(*DiagnosticOpts, Args, SA, false);
4614   GenerateFrontendArgs(FrontendOpts, Args, SA, LangOpts->IsHeaderFile);
4615   GenerateTargetArgs(*TargetOpts, Args, SA);
4616   GenerateHeaderSearchArgs(*HeaderSearchOpts, Args, SA);
4617   GenerateLangArgs(*LangOpts, Args, SA, T, FrontendOpts.DashX);
4618   GenerateCodeGenArgs(CodeGenOpts, Args, SA, T, FrontendOpts.OutputFile,
4619                       &*LangOpts);
4620   GeneratePreprocessorArgs(*PreprocessorOpts, Args, SA, *LangOpts, FrontendOpts,
4621                            CodeGenOpts);
4622   GeneratePreprocessorOutputArgs(PreprocessorOutputOpts, Args, SA,
4623                                  FrontendOpts.ProgramAction);
4624   GenerateDependencyOutputArgs(DependencyOutputOpts, Args, SA);
4625 }
4626 
4627 std::vector<std::string> CompilerInvocation::getCC1CommandLine() const {
4628   // Set up string allocator.
4629   llvm::BumpPtrAllocator Alloc;
4630   llvm::StringSaver Strings(Alloc);
4631   auto SA = [&Strings](const Twine &Arg) { return Strings.save(Arg).data(); };
4632 
4633   // Synthesize full command line from the CompilerInvocation, including "-cc1".
4634   SmallVector<const char *, 32> Args{"-cc1"};
4635   generateCC1CommandLine(Args, SA);
4636 
4637   // Convert arguments to the return type.
4638   return std::vector<std::string>{Args.begin(), Args.end()};
4639 }
4640 
4641 void CompilerInvocation::resetNonModularOptions() {
4642   getLangOpts()->resetNonModularOptions();
4643   getPreprocessorOpts().resetNonModularOptions();
4644 }
4645 
4646 void CompilerInvocation::clearImplicitModuleBuildOptions() {
4647   getLangOpts()->ImplicitModules = false;
4648   getHeaderSearchOpts().ImplicitModuleMaps = false;
4649   getHeaderSearchOpts().ModuleCachePath.clear();
4650   getHeaderSearchOpts().ModulesValidateOncePerBuildSession = false;
4651   getHeaderSearchOpts().BuildSessionTimestamp = 0;
4652   // The specific values we canonicalize to for pruning don't affect behaviour,
4653   /// so use the default values so they may be dropped from the command-line.
4654   getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60;
4655   getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60;
4656 }
4657 
4658 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
4659 clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI,
4660                                        DiagnosticsEngine &Diags) {
4661   return createVFSFromCompilerInvocation(CI, Diags,
4662                                          llvm::vfs::getRealFileSystem());
4663 }
4664 
4665 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
4666 clang::createVFSFromCompilerInvocation(
4667     const CompilerInvocation &CI, DiagnosticsEngine &Diags,
4668     IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
4669   return createVFSFromOverlayFiles(CI.getHeaderSearchOpts().VFSOverlayFiles,
4670                                    Diags, std::move(BaseFS));
4671 }
4672 
4673 IntrusiveRefCntPtr<llvm::vfs::FileSystem> clang::createVFSFromOverlayFiles(
4674     ArrayRef<std::string> VFSOverlayFiles, DiagnosticsEngine &Diags,
4675     IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
4676   if (VFSOverlayFiles.empty())
4677     return BaseFS;
4678 
4679   IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
4680   // earlier vfs files are on the bottom
4681   for (const auto &File : VFSOverlayFiles) {
4682     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
4683         Result->getBufferForFile(File);
4684     if (!Buffer) {
4685       Diags.Report(diag::err_missing_vfs_overlay_file) << File;
4686       continue;
4687     }
4688 
4689     IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
4690         std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
4691         /*DiagContext*/ nullptr, Result);
4692     if (!FS) {
4693       Diags.Report(diag::err_invalid_vfs_overlay) << File;
4694       continue;
4695     }
4696 
4697     Result = FS;
4698   }
4699   return Result;
4700 }
4701