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