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