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